<!--
 * @页面名称: 动态窗体模型
 * @描述: 主页面
 * @修改: 
 * @Date: 
 -->
<template>
  <div class="main-box">
    <splitpanes :dbl-click-splitter="false" class="default-theme" @resize="handleResize">
      <pane :size="leftPaneSize">
        <div class="card tree">
          <left-tree ref="leftTree" @onClick="onTreeClick" @noClassManage="noClassManage" @recycle="recycle"></left-tree>
        </div>
      </pane>
      <pane :size="100 - leftPaneSize">
        <div class="table-box">
          <splitpanes
            horizontal
            :dbl-click-splitter="false"
            :class="`default-theme ${tableSearch ? 'table-content' : '.table-default'}`"
            @resize="handleMiddleResize"
          >
            <!--   -->
            <pane :size="middlePaneSize">
              <div class="card table-main">
                <div class="tableWraper" :style="{ height: '100%' }">
                  <!-- 眼睛icon -->
                  <!-- <div class="showIcon" v-show="topBarShow">
                    <el-button :icon="tableSearch ? 'View' : 'Hide'" circle @click="trigger" />
                  </div> -->
                  <!-- 表格 -->
                  <TableBar
                    ref="tabbarRef"
                    columnType="folder"
                    :name="'tabbarRef'"
                    :father="{}"
                    :tableSearch="tableSearch"
                    :searchSetting="searchSetting.visible"
                    :fmtData="FMTData"
                    :childs="childTabbarRef"
                    :columns="tableSetting.columns"
                    :loading="tableSetting.loading"
                    :childData="childData"
                    :paginationShow="dynamicStore.isShowPage"
                    :hasTableData="dynamicStore.tableData.length > 0"
                    :tableMenu="tableSetting.tableMenu"
                    :toolbarConfig="tableSetting.toolbarConfig"
                    @trigger="trigger"
                    @rowClick="rowClick"
                    @rowdblClick="rowdblClick"
                    @selectChange="tableSelect"
                    @pageNext="pageNext"
                    @pageAll="pageAll"
                    @viewFullText="viewFullText"
                    @toSublevel="toSublevel"
                    @menuClick="menuClick"
                    @showMetaData="showFolderMetaData"
                    @refresh="tableRefresh"
                    @showFourAspectRecords="showFourAspectRecords"
                    @fileDrop="handleParentFileDrop"
                  >
                    <template #toolbarButtons>
                      <TopBar
                        v-if="topBarShow"
                        type="parentButton"
                        :reportData="reportData"
                        @buttonClick="buttonClick"
                        @exportExcel="exportExcel"
                        @reportExcel="reportExcel"
                        @trigger="trigger"
                      ></TopBar>
                      <el-space v-if="recycleStatus">
                        <el-button @click="restore" :disabled="recycleBtnStatus[0]">还原</el-button>
                        <el-button type="danger" @click="recycleDel" :disabled="recycleBtnStatus[1]">删除</el-button>
                      </el-space>
                    </template>
                  </TableBar>
                </div>
              </div>
            </pane>
            <!-- 子级表格 -->
            <pane :size="100 - middlePaneSize" v-if="globalStore.showChild && childData.length > 0">
              <el-tabs v-model="activeName" class="demo-tabs" style="height: 100%" @tab-change="tabChange">
                <el-tab-pane style="height: 100%" v-for="(item, index) in childData" :key="index" :label="item.FMT_Name">
                  <div class="card table-main">
                    <div style="height: 100%">
                      <TableBar
                        ref="childTabbarRef"
                        columnType="file"
                        :name="'childTabbarRef'"
                        :fmtData="FMTData"
                        :father="tabbarRef"
                        :childData="childTableSetting.childDataByChildTable"
                        :columns="childTableSetting.childColumns"
                        :loading="childTableSetting.childLoading"
                        :tableMenu="childTableSetting.tableMenu"
                        :toolbarConfig="childTableSetting.toolbarConfig"
                        @rowClick="childRowClick"
                        @rowdblClick="childRowdblClick"
                        @selectChange="childTableSelect"
                        @viewFullText="childViewFullText"
                        @toSublevel="childToSublevel"
                        @showMetaData="showFileMetaData"
                        @menuClick="menuClick"
                        @showFourAspectRecords="showFourAspectRecords"
                        @refresh="getChildTableData"
                        @fileDrop="handleChildFileDrop"
                      >
                        <template #toolbarButtons>
                          <TopBar
                            v-if="childTableSetting.childTopBarShow"
                            type="childButton"
                            :reportData="childReportData"
                            @buttonClick="childButtonClick"
                            @exportExcel="exportExcel"
                            @reportExcel="childReportExcel"
                          ></TopBar>
                        </template>
                      </TableBar>
                    </div>
                  </div>
                </el-tab-pane>
              </el-tabs>
            </pane>
          </splitpanes>
        </div>
      </pane>
    </splitpanes>
    <!-- 动态表单弹出框(主业务) -->
    <dynamic-form ref="dynamicForm" :dynamicModal="dynamicModal" :self="self"></dynamic-form>
    <!-- SingalrModal弹框/在此页面用于展示删除数据的详情进度 -->
    <SingalrModal
      v-model:visible="singalrModal.visible"
      :discontinueFont="singalrModal.discontinueFont"
      :percentage="singalrModal.percent"
      @cease="cease"
      @cancel="cancel"
      width="50vw"
    >
      <!-- 添加暂停状态指示 -->
      <div class="pause-status-indicator" v-if="singalrModal.discontinueStatus">
        <el-tag type="warning" size="small">
          <el-icon><Clock /></el-icon>
          {{ singalrModal.networkStatus && singalrModal.AllNetworkStatus ? "处理中" : "已暂停" }}
        </el-tag>
      </div>

      <!-- 原有的进度文本 -->
      <div class="progress-text">
        {{ singalrModal.text }}
      </div>
    </SingalrModal>
    <!-- 查看全文抽屉 -->
    <el-drawer v-model="drawerSetting.visible" :title="drawerSetting.title" :show-close="true" size="65%" direction="btt">
      <FullText ref="fulltextRef"></FullText>
    </el-drawer>
    <!-- 元数据抽屉 -->
    <el-drawer v-model="metaDataSetting.visible" title="元数据" direction="rtl" :show-close="true" size="75%">
      <MetaData ref="metaDataRef"></MetaData>
    </el-drawer>
    <!-- 目录二维码弹出框 -->
    <QRCode1 ref="QRCode1"></QRCode1>
    <!-- 数据二维码弹出框 -->
    <QRCode2 ref="QRCode2"></QRCode2>
    <!-- 修改分类 -->
    <SortModal
      ref="SortModalRef"
      :type="dynamicModal.type"
      :fmtObj="childData.filter((v: any) => v.FMT_ID)"
      :activeName="activeName"
    ></SortModal>
    <!-- 移交下一环节 -->
    <HandOverModal ref="HandOverModalRef" :handoverSetting="handoverSetting"></HandOverModal>
    <!-- 批量挂接全文 -->
    <input ref="uploadZip" accept=".zip" type="file" @change="uploadZipFile" style="display: none" />
    <!-- 全文批量挂接modal -->
    <el-dialog draggable v-model="uploadConfig.visible" title="批量挂接全文" width="500px">
      <span>是否覆盖:</span>
      <el-checkbox v-model="uploadConfig.isCover"></el-checkbox>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="uploadConfig.visible = false">取消</el-button>
          <el-button type="primary" @click="fulltextUploadMany">确定</el-button>
        </span>
      </template>
    </el-dialog>
    <!-- 轨迹查看 -->
    <Trail ref="TrailRef" :config="TrailConfig"></Trail>
    <!-- 权限管理 -->
    <AuthorityManage :config="AuthConfig"></AuthorityManage>
    <!-- 文件上传进度条 -->
    <el-dialog
      title="正在上传文件...请稍等"
      v-model="fulltextModal.isShow"
      width="30%"
      class="progress-modal"
      top="300px"
      center
      :close-on-click-modal="false"
      :showClose="false"
    >
      <template #footer>
        <span class="dialog-footer">
          <el-progress :text-inside="true" :stroke-width="20" :percentage="fulltextModal.percent" status="success" />
        </span>
      </template>
    </el-dialog>
    <!-- 离线挂载 -->
    <modal v-model:visible="mountSetting.visible" :title="mountSetting.title" width="650" @ok="mountHandle">
      <el-form :model="formData" ref="mountForm" :rules="mountRule" label-width="120px">
        <el-form-item label="挂载地址" prop="path">
          <el-input v-model="formData.path" placeholder="请输入离线挂载路径,如/GJTEST/" />
        </el-form-item>
        <el-form-item label="是否覆盖" prop="isCover">
          <el-checkbox v-model="formData.isCover" />
        </el-form-item>
        <el-form-item label="采用顺序号挂接" prop="IsOrder">
          <el-checkbox v-model="formData.isOrder" />
        </el-form-item>
      </el-form>
    </modal>
    <!-- 粘贴剪贴弹框 -->
    <modal class="pasteModal" v-model:visible="pasteSetting.visible" :title="pasteSetting.title" width="500" @ok="pasteHandle">
      <el-form :model="pasteFormData" ref="pasteForm">
        <el-form-item>
          <el-checkbox v-model="pasteFormData.isTrue">粘贴全文数据</el-checkbox>
        </el-form-item>
      </el-form>
    </modal>
    <!-- 重置流水号弹框 -->
    <modal v-model:visible="resetLSH.visible" :title="resetLSH.title" width="500" @ok="resetLSHHandle">
      <el-form :model="resetLSHFormData" :rules="LHSRule" ref="resetLHSRef">
        <el-form-item label="起始流水号" prop="lsh_start">
          <el-input v-model.number="resetLSHFormData.lsh_start"></el-input>
        </el-form-item>
      </el-form>
    </modal>
    <!-- 流水号移至 -->
    <modal v-model:visible="LSHMoveSetting.visible" :title="LSHMoveSetting.title" width="500" @ok="LSHMoveHandle">
      <el-form :model="LSHMoveFormData">
        <el-form-item label="移至流水号">
          <el-input v-model="LSHMoveFormData.moveOrder"></el-input>
        </el-form-item>
      </el-form>
    </modal>
    <!-- 标记备注弹框 -->
    <modal v-model:visible="remarkSetting.visible" :title="remarkSetting.title" width="600" height="100" @ok="remarkHandle">
      <el-form :model="remarkFormData" ref="remarkForm">
        <el-form-item label="取消标注：">
          <el-checkbox @change="remarkChange" v-model="remarkFormData.remark" />
        </el-form-item>
        <el-form-item label="标注内容：">
          <el-input v-model="remarkFormData.content" />
        </el-form-item>
        <el-form-item label="标注颜色：">
          <!-- <el-color-picker v-model="remarkFormData.color" /> -->
          <el-color-picker-panel v-model="remarkFormData.color" />
        </el-form-item>
      </el-form>
    </modal>
    <!-- 数据查重弹框 -->
    <modal v-model:visible="dataCheckSetting.visible" :title="dataCheckSetting.title" width="500" @ok="dataCheckHandle">
      <el-form :model="dataCheckFormData" ref="dataCheckForm" :rules="dataCheckRule">
        <el-form-item label="选择查询字段:" prop="field">
          <!-- <el-input v-model="dataCheckFormData.field" /> -->
          <el-select v-model="dataCheckFormData.field" multiple clearable style="width: 100%">
            <el-option
              v-for="item in dataCheckSetting.type === 'folder' ? tableSetting.columns : childTableSetting.childColumns"
              :key="item.DDM_ID"
              :value="item.Field_Name"
              :label="item.DDM_CNName + '(' + item.Field_Name + ')'"
            >
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
    </modal>
    <!-- 查找替换 -->
    <Replacement ref="replaceModal" :config="ReplacementConfig"></Replacement>
    <!-- 拆卷 -->
    <modal v-model:visible="dismantleSetting.visible" :title="dismantleSetting.title" width="500" @ok="dismantleHandle">
      <el-checkbox v-model="dismantleSetting.isTrue">是否清除分类</el-checkbox>
    </modal>
    <!-- 查询归卷 -->
    <modal
      class="queryTheVolume_dialog"
      v-model:visible="queryTheVolumeSetting.visible"
      :title="queryTheVolumeSetting.title"
      width="90%"
      @ok="queryTheVolumeHandle"
    >
      <splitpanes :dbl-click-splitter="false" class="default-theme">
        <pane :size="20">
          <el-card>
            <div class="left">
              <el-select @change="queryTheVolumeSelectChange" v-model="queryTheVolumeSelect" placeholder="请选择归卷数据表">
                <el-option
                  v-for="item in (FMTData as any[]).filter((v: any) => v.FMT_Parent_ID === tableSetting.rowClickObj?.FMT_ID)"
                  :key="item.FMT_ID"
                  :label="item.FMT_Name"
                  :value="item.FMT_ID"
                />
              </el-select>
              <div class="queryTheVolume_content_left">
                <QueryTheVolumnLeftTree @onClick="onQueryTheVolumeTreeClick" @noClassManage="noQueryTheVolumeTreeClassMana">
                </QueryTheVolumnLeftTree>
              </div>
            </div>
          </el-card>
        </pane>
        <pane :size="80">
          <el-card>
            <div class="queryTheVolume_content">
              <div class="queryTheVolume_content_right">
                <div class="table-top">
                  <el-input
                    v-model="queryTheVolumeInput"
                    @input="queryTheVolumeInputChange"
                    placeholder="请输入查询条件"
                  ></el-input>
                  <span style="font-size: 18px; font-weight: bold">共{{ queryTheVolumeTableSetting.data.length }}条数据</span>
                </div>
                <Stable
                  :columns="queryTheVolumeTableSetting.columns"
                  :data="queryTheVolumeTableSetting.data"
                  @selectionChange="queryTheVolumeTableSelect"
                ></Stable>
              </div>
            </div>
          </el-card>
        </pane>
      </splitpanes>
    </modal>
    <!-- 流水号操作弹框 -->
    <modal class="LSH_dialog" v-model:visible="LSHSetting.visible" :title="LSHSetting.title" width="80%" @ok="LSHandle">
      <el-space style="margin-bottom: 10px">
        <el-button :loading="LSHSetting.btnLoading" @click="resetLSHEvent">重置流水号</el-button>
        <el-button :loading="LSHSetting.btnLoading2" @click="sortUpLSH(LSHSetting.LShTableIndex)">流水号上移</el-button>
        <el-button :loading="LSHSetting.btnLoading3" @click="sortDownLSH(LSHSetting.LShTableIndex)">流水号下移</el-button>
        <el-button :loading="LSHSetting.btnLoading4" @click="LSHTo()">流水号移至</el-button>
        <el-input placeholder="请输入起始流水号" v-model="LSHSetting.startLSH"></el-input>
        <el-input placeholder="请输入要移至的流水号" v-model="LSHSetting.endLSH"></el-input>
        <span style="font-size: 18px; font-weight: bold">共{{ LSHSetting.data.length }}条数据</span>
      </el-space>
      <div class="LSH_content" style="height: calc(60vh - 42px)">
        <Stable
          ref="lshTable"
          :columns="LSHSetting.type === 1 ? LSHSetting.columns : LSHSetting.columns2"
          :data="LSHSetting.data"
          :loading="LSHSetting.loading"
          :loadingText="LSHSetting.loadingText"
          @rowClick="LSHRowClick"
        ></Stable>
      </div>
    </modal>
    <!-- 搜索弹框 -->
    <el-dialog v-model="searchSetting.visible" :title="searchSetting.title" width="40%" draggable overflow>
      <!-- <div class="btns"></div> -->
      <el-form class="search-wrap" :inline="true" :model="formModel" ref="formRef">
        <el-row>
          <el-col v-for="item in searchFieldData" :key="item.DDM_ID" :span="24">
            <el-form-item style="width: 100%" :prop="item.Field_Name" :label="item.DDM_CNName + ':'" label-width="120px">
              <!-- 分类 -->
              <el-tree-select
                v-if="item.Field_Name === 'Catalog_ID'"
                style="width: 100%"
                check-strictly
                clearable
                v-model="formModel[item.Field_Name]"
                node-key="Catalog_ID"
                :props="{ label: 'Catalog_Name', children: 'children' }"
                :data="transTree(catalogList, 'Catalog_ID', 'Catalog_Father')"
                :render-after-expand="false"
              />
              <!-- 是否锁住 -->
              <el-checkbox v-else-if="item.Field_Name === 'IsLock'" v-model="formModel[item.Field_Name]" />
              <div v-else-if="item.DataType == 'datetime'" style="width: 100%">
                <el-date-picker style="width: 100%" v-model="formModel[item.Field_Name]" type="date" placeholder="请选择日期" />
              </div>

              <el-select v-else-if="item.FR_TableField" v-model="formModel[item.Field_Name]" clearable style="width: 100%">
                <el-option
                  v-for="item2 in dictionary[item.FR_TableField]"
                  :key="item2.DDL_ID"
                  :label="item2.DDL_Name"
                  :value="item2.DDL_ID"
                >
                </el-option>
              </el-select>
              <el-select v-else-if="item.FR_TableField2" v-model="formModel[item.Field_Name]" clearable style="width: 100%">
                <el-option v-for="item2 in userList" :key="item2.U_ID" :label="item2.U_Name" :value="item2.U_ID"> </el-option>
              </el-select>
              <el-input v-else v-model="formModel[item.Field_Name]" placeholder="请输入" />
            </el-form-item>
          </el-col>
          <el-col :span="16">
            <el-form-item style="width: 100%" prop="FuzzyQuery" label="模糊查询:" label-width="80px">
              <el-checkbox v-model="formModel.FuzzyQuery" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <div class="btns">
              <el-button type="primary" icon="Search" @click="search">搜索</el-button>
              <el-button icon="Delete" @click="reset(formRef)">重置</el-button>
            </div>
          </el-col>
        </el-row>
      </el-form>
      <!-- <template #footer>
        <span class="dialog-footer">
          <el-button type="primary" @click="searchHandle">关闭</el-button>
        </span>
      </template> -->
    </el-dialog>
    <!-- 四性检测 -->
    <!-- <el-dialog v-model="fourAspectShow" width="800" :close-on-click-modal="false" draggable> -->
    <FourAspect
      ref="fourAspectRef"
      v-if="fourAspectShow"
      :fourAspectConfigs="fourAspectConfigs"
      :fourAspectRow="fourAspectRow"
      :curFourAspectItem="curFourAspectItem"
      :allFinish="allFinish"
      :activeIndex="activeIndex"
      :selectedCount="tableSetting.selectData.length + childTableSetting.selectData.length"
      @startCheck="seletedDataHandle"
      @stopCheck="stopCheckHandle"
      @closeModal="fourAspectShow = false"
    />
    <!-- </el-dialog> -->
    <!-- 四性检测记录展示 -->
    <el-drawer v-model="isShowFourAspectRecords" title="四性检测记录" direction="btt" size="60%">
      <FourAspectRecords v-if="isShowFourAspectRecords" :fourAspectRecordsClickRow="fourAspectRecordsClickRow" />
    </el-drawer>
    <!-- url借阅 -->
    <UrlBorrow ref="UrlBorrowRef" v-model:visible="urlModal.isShow" width="80%" @ok="urlBorrow"> </UrlBorrow>
    <!-- 合卷 -->
    <RollUp ref="RollUpForm" :rollUpConfig="rollUpConfig"> </RollUp>
    <!-- 设置标签 -->
    <el-drawer v-model="LabelSetting.visible" :title="LabelSetting.title" direction="rtl" size="20%">
      <div class="label_box">
        <div v-for="group in groupedLabels" :key="group.titleId" class="label_group">
          <div class="label_group_title">{{ group.title }}</div>
          <div class="label_group_items">
            <div
              class="label_box_item"
              v-for="item in group.children"
              :key="item.DDL_ID"
              :class="[
                { selected: selectedItems[dictionary['labels'].findIndex((label: any) => label.DDL_ID === item.DDL_ID)] },
                getLabelClass(item.DDL_ID)
              ]"
              @click="toggleSelection(dictionary['labels'].findIndex((label: any) => label.DDL_ID === item.DDL_ID))"
              :data-index="dictionary['labels'].findIndex((label: any) => label.DDL_ID === item.DDL_ID) + 1"
            >
              <el-tooltip
                v-if="item.DDL_Name.length > 4"
                class="box-item"
                effect="dark"
                :content="item.DDL_Name"
                placement="top-start"
              >
                <span> {{ item.DDL_Name }}</span>
              </el-tooltip>
              <span v-else> {{ item.DDL_Name }}</span>
            </div>
          </div>
        </div>
      </div>
      <template #footer>
        <div style="flex: auto">
          <el-button @click="LabelSetting.visible = false">取消</el-button>
          <el-button type="primary" @click="LabelHandle">确认</el-button>
        </div>
      </template>
    </el-drawer>
    <!-- 搜索标签 -->
    <el-drawer v-model="LabelSearchSetting.visible" :title="LabelSearchSetting.title" direction="rtl" size="20%">
      <div class="label_box">
        <div v-for="group in groupedLabels" :key="group.titleId" class="label_group">
          <div class="label_group_title">{{ group.title }}</div>
          <div class="label_group_items">
            <div
              class="label_box_item"
              v-for="item in group.children"
              :key="item.DDL_ID"
              :class="{ selected: selectedItems[dictionary['labels'].findIndex((label: any) => label.DDL_ID === item.DDL_ID)] }"
              @click="toggleSelection(dictionary['labels'].findIndex((label: any) => label.DDL_ID === item.DDL_ID))"
              :data-index="dictionary['labels'].findIndex((label: any) => label.DDL_ID === item.DDL_ID) + 1"
            >
              <el-tooltip
                v-if="item.DDL_Name.length > 4"
                class="box-item"
                effect="dark"
                :content="item.DDL_Name"
                placement="top-start"
              >
                <span> {{ item.DDL_Name }}</span>
              </el-tooltip>
              <span v-else> {{ item.DDL_Name }}</span>
            </div>
          </div>
        </div>
      </div>
    </el-drawer>
    <!-- 子级设置标签 -->
    <el-drawer v-model="LabelSetting2.visible" :title="LabelSetting2.title" direction="rtl" size="20%">
      <div class="label_box">
        <div v-for="group in groupedLabels" :key="group.titleId" class="label_group">
          <div class="label_group_title">{{ group.title }}</div>
          <div class="label_group_items">
            <div
              class="label_box_item"
              v-for="item in group.children"
              :key="item.DDL_ID"
              :class="[
                { selected: selectedItems2[dictionary['labels'].findIndex((label: any) => label.DDL_ID === item.DDL_ID)] },
                getLabelClass2(item.DDL_ID)
              ]"
              @click="toggleSelection2(dictionary['labels'].findIndex((label: any) => label.DDL_ID === item.DDL_ID))"
              :data-index="dictionary['labels'].findIndex((label: any) => label.DDL_ID === item.DDL_ID) + 1"
            >
              <el-tooltip
                v-if="item.DDL_Name.length > 4"
                class="box-item"
                effect="dark"
                :content="item.DDL_Name"
                placement="top-start"
              >
                <span> {{ item.DDL_Name }}</span>
              </el-tooltip>
              <span v-else> {{ item.DDL_Name }}</span>
            </div>
          </div>
        </div>
      </div>
      <template #footer>
        <div style="flex: auto">
          <el-button @click="LabelSetting2.visible = false">取消</el-button>
          <el-button type="primary" @click="LabelHandle2">确认</el-button>
        </div>
      </template>
    </el-drawer>
    <!-- 子级搜索标签 -->
    <el-drawer v-model="LabelSearchSetting2.visible" :title="LabelSearchSetting2.title" direction="rtl" size="20%">
      <div class="label_box">
        <div v-for="group in groupedLabels" :key="group.titleId" class="label_group">
          <div class="label_group_title">{{ group.title }}</div>
          <div class="label_group_items">
            <div
              class="label_box_item"
              v-for="item in group.children"
              :key="item.DDL_ID"
              :class="{ selected: selectedItems2[dictionary['labels'].findIndex((label: any) => label.DDL_ID === item.DDL_ID)] }"
              @click="toggleSelection2(dictionary['labels'].findIndex((label: any) => label.DDL_ID === item.DDL_ID))"
              :data-index="dictionary['labels'].findIndex((label: any) => label.DDL_ID === item.DDL_ID) + 1"
            >
              <el-tooltip
                v-if="item.DDL_Name.length > 4"
                class="box-item"
                effect="dark"
                :content="item.DDL_Name"
                placement="top-start"
              >
                <span> {{ item.DDL_Name }}</span>
              </el-tooltip>
              <span v-else> {{ item.DDL_Name }}</span>
            </div>
          </div>
        </div>
      </div>
    </el-drawer>
  </div>
</template>

<script lang="tsx">
import {
  reactive,
  onMounted,
  ref,
  getCurrentInstance,
  nextTick,
  defineComponent,
  watch,
  computed,
  onActivated,
  onDeactivated
} from "vue";
import type { FormInstance } from "element-plus";
import UrlBorrow from "../../../components/UrlBorrow/index.vue";
import DynamicForm from "./DynamicForm.vue";
import LeftTree from "./components/LeftTree/LeftTree.vue";
import TableBar from "./components/TableBar/index.vue";
import TopBar from "./components/TopBar/index.vue";
import FullText from "./components/FullText/FullText.vue";
import QRCode1 from "./components/QRCode/QRCode1.vue";
import QRCode2 from "./components/QRCode/QRCode2.vue";
import AuthorityManage from "./components/AuthorityManage/index.vue";
import { SortModal } from "./components";
import HandOverModal from "./components/handoverModal/index.vue";
import Replacement from "./components/Replacement/index.vue";
import MetaData from "./components/metaData/index.vue";
import Trail from "./components/trail/index.vue";
import QueryTheVolumnLeftTree from "./components/LeftTree/QueryTheVolumeLeftTree.vue";
import Stable from "@/components/Stable/index.vue";
import { useRouter, useRoute } from "vue-router";
import { ButtonClick } from "./events";
import { useDynamicStore } from "@/stores/modules/dynamic";
import { useDictionryStore } from "@/stores/modules/dictionary";
import { useUserStore } from "@/stores/modules/user";
import { useGlobalStore } from "@/stores/modules/global";
import { useCatalogStore } from "@/stores/modules/catalog";
import { useAppStore } from "@/stores/modules/app";
import { useDynamicButtonStore } from "@/stores/modules/dynamicButton";
import { defaultVisibleColumn } from "./ts/columnData";
import { Splitpanes, Pane } from "splitpanes";
import "splitpanes/dist/splitpanes.css";
import { transTree, getSysConfig } from "@/utils/util";
import { ButtonStatus } from "./components/TopBar/InitButton";
import { Excel } from "@/utils/reportUpload2";
import RuleClass from "./ts/FieldRule";
import { useFormatter } from "@/hooks/useFormatter";
import ACrypto from "@/utils/crypto";
import { cloneDeep, isEqual } from "lodash-es";
import useCurrentInstance from "@/utils/useCurrentInstance";
import { columnCoverter } from "@/views/system/dynamicMain/ts/until";
import FourAspect from "./components/FourAspect/index.vue";
import FourAspectRecords from "./components/FourAspect/FourAspectRecords.vue";
import RollUp from "./components/RollUp/index.vue";
import dtime from "moment";
import mittBus from "@/utils/mittBus";
import global from "@/utils/SnowflakeClass";

export default defineComponent({
  components: {
    FullText,
    DynamicForm,
    LeftTree,
    TableBar,
    TopBar,
    QRCode1,
    QRCode2,
    SortModal,
    HandOverModal,
    Splitpanes,
    Pane,
    Trail,
    AuthorityManage,
    Replacement,
    MetaData,
    QueryTheVolumnLeftTree,
    Stable,
    FourAspect,
    FourAspectRecords,
    UrlBorrow,
    RollUp
  },
  setup() {
    // 表格字段转换
    const formatter = ({ row, column, cellValue }: any): any => {
      const catalogList = catalogStore.catalogList;
      let ruleList = [];
      ruleList = dynamicStore.childVisibleConfig.FieldRule.filter((v: any) => v.FR_RuleType === "display");
      const tempObj = ruleList.find((v: any) => v.FR_TableField === column.property);
      let result = null;
      let param = null;

      if (tempObj) {
        // 字典转换
        param = tempObj.FR_Rule.split(":")[1];
        if (tempObj.FR_Rule.includes("dictionary:")) {
          result = columnCoverter(tempObj.FR_Rule, cellValue);
        } else if (tempObj.FR_Rule.toLowerCase().includes("datetime:")) {
          // 时间转换
          result = row[tempObj.FR_TableField] ? dtime(row[tempObj.FR_TableField]).format(param) : "";
        } else if (tempObj.FR_Rule.toLowerCase().includes("userinfo:")) {
          // 人员的id转换
          const temp = userStore.getUserList.find((v: any) => v.U_ID === cellValue);
          result = temp ? temp[param] : "";
        } else if (tempObj.FR_Rule.toLowerCase().includes("catalogconvert:")) {
          // 分类id转换
          const temp = catalogList.find((v: any) => v.Catalog_ID && v.Catalog_ID === cellValue);
          console.log(temp, param);
          result = temp ? temp[param] : "";
        } else if (tempObj.FR_Rule.toLowerCase().includes("orgconvert:")) {
          const temp = catalogList.find(v => v[tempObj.Field_Name] === cellValue);
          result = temp ? temp[param] : "";
        } else if (tempObj.FR_Rule.toLowerCase().includes("jm")) {
          // 对加密字段转换
          result = ACrypto.getSS(row[tempObj.FR_TableField]);
        } else if (tempObj.FR_Rule.toLowerCase().includes("tozh")) {
          if (row[tempObj.FR_TableField]) {
            result = "是";
          } else {
            result = "否";
          }
        }
      }
      if (result) {
        return result;
      }
      return cellValue;
    };
    // 头部按钮是否显示
    const topBarShow = ref(false);
    // 头部按钮高度
    const headerHeight = ref(0);
    // 表格高度
    const tableHeight = ref(100);
    // 动态计算表格高度
    const sumHeight = computed(() => {
      return `calc(${tableHeight.value}% - ${headerHeight.value}px)`;
    });
    // 子级头部按钮高度
    const childHeaderHeight = ref(0);
    // 子级表格高度
    const childTableHeight = ref(100);
    // 子级表格高度
    const childHeight = computed(() => {
      return `calc(${childTableHeight.value}% - ${childHeaderHeight.value}px)`;
    });
    // 按钮状态实例
    const buttonStatus = new ButtonStatus();
    const { proxy } = getCurrentInstance() as any;
    // pinia数据
    const dictionryStore = useDictionryStore();
    const globalStore = useGlobalStore();
    const userStore = useUserStore();
    const catalogStore = useCatalogStore();
    const appStore = useAppStore();
    const dynamicButtonStore = useDynamicButtonStore();
    // 字典数据
    const dictionary = dictionryStore.getDictionaryObj;
    // 搜索功能分类数据
    const catalogList = ref([]);
    // 搜索字段
    const searchFieldData = ref<any>([]);
    // 顶部搜索表单绑定字段
    const formModel: any = reactive({
      FuzzyQuery: true
    });
    // 表单实例
    const formRef = ref<FormInstance>();
    // 搜索是否显示
    const tableSearch = ref(false);
    // 目录二维码弹框实例
    const QRCode1 = ref();
    // 数据二维码弹框实例
    const QRCode2 = ref();
    // 修改分类弹出框
    const SortModalRef = ref();
    // 轨迹查看弹出框
    const TrailRef = ref();
    // 轨迹查看弹框配置
    const TrailConfig = reactive({
      // 轨迹查看弹框是否显示
      visible: false,
      // 轨迹查看弹框标题
      title: "",
      // 轨迹查看弹框数据
      data: {} as any
    });
    // 权限管理配置
    const AuthConfig = reactive({
      visible: false,
      title: "",
      type: 1
    });
    // 获取路由
    const router = useRouter();
    const route = useRoute();
    // 路由携带的参数
    const routeData = ref(route.query as any);
    // 父级对象
    const fatherObj = routeData.value.fatherObj ? JSON.parse(decodeURIComponent(routeData.value.fatherObj as any)) : undefined;

    // 文件拖拽处理函数
    const handleParentFileDrop = async (data: { files: File[]; columnType: string }) => {
      const { files, columnType } = data;
      if (columnType === "folder") {
        // 检查新增权限 - 与 TopBar 中的 toggleDisabled 新增按钮逻辑保持一致
        let hasAddPermission = false;
        const isCanAdd = getSysConfig("parentNodeCanAdd");

        // 判断是否是通过父表进入的子表
        if (routeData.value.fatherObj && !dynamicStore.childLeftClick && !dynamicStore.noCatalogStatus) {
          const fatherObj = JSON.parse(decodeURIComponent(routeData.value.fatherObj));
          // 检查父表状态是否允许新增
          if (![1, 12].includes(fatherObj?.Status) && routeData.value.status === "Collect") {
            proxy.$message.warning("当前状态不允许新增");
            return;
          }
          // 检查父表分类的权限
          if (fatherObj.Catalog_ID) {
            const catalogItem = catalogStore.catalogList.find((v: any) => v.Catalog_ID === fatherObj.Catalog_ID);
            if (catalogItem && catalogItem.PC_PermissionStr) {
              const permissionStr = JSON.parse(catalogItem.PC_PermissionStr);
              hasAddPermission = permissionStr[0] && permissionStr[0].includes("新增");
            }
          }
        } else {
          // 检查当前节点的权限
          if (catalogStore.treeNode && catalogStore.treeNode.PC_PermissionStr) {
            const permissionStr = JSON.parse(catalogStore.treeNode.PC_PermissionStr);
            hasAddPermission = permissionStr[0] && permissionStr[0].includes("新增");
          }
          // 检查是否配置了叶子节点新增限制
          if (isCanAdd !== "1" && catalogStore.treeNode?.children) {
            proxy.$message.warning("当前节点不允许新增");
            return;
          }
        }

        if (!hasAddPermission) {
          proxy.$message.warning("暂无上传权限");
          return;
        }

        // 显示加载状态
        proxy.$showLoading({ tip: `正在处理 ${files.length} 个文件...` });

        try {
          // 处理父级表格文件拖拽
          for (const file of files) {
            // 获取文件名（不包含扩展名）
            const fileName = file.name.replace(/\.[^/.]+$/, "");
            const currentYear = new Date().getFullYear();
            const currentCatalog = catalogStore.treeNode?.Catalog_ID || "";
            const stateNum: any = {
              Collect: 1,
              Arrangement: 2,
              Storage: 3,
              Utilization: 4
            };
            // 创建新数据对象
            const newData = {
              Order: "",
              SmallOrder: "",
              Year: currentYear,
              Title: fileName,
              Record_ID: global.createID(),
              Catalog_ID: dynamicStore.noCatalogStatus ? null : currentCatalog,
              Fonds_ID: catalogStore.treeNode?.Fonds_ID || "",
              Parent_ID: fatherObj?.Record_ID ? fatherObj.Record_ID : "",
              Create_DateTime: new Date(),
              FMT_ID: routeData.value.fmtid,
              FM_ID: routeData.value.fmid,
              Status: stateNum[routeData.value.status]
            };
            const ruleList = dynamicStore.visibleConfig.FieldRule.filter(
              (v: any) => v.FR_Enable === true || v.FR_Rule.toLowerCase().includes("jm")
            );
            const FieldRuleClass = new RuleClass({ modalFormData: newData, ruleList });
            const newModalFormData = FieldRuleClass.ReSetEncrypt();
            if (ruleList && ruleList.length && ruleList.length > 0) {
              const FieldRuleClass = new RuleClass({
                modalFormData: newModalFormData,
                ruleList,
                tableName: dynamicStore.visibleConfig.FMT.FMT_TableName
              }); // 执行字段规则类方法
              await FieldRuleClass.fieldRuleEvent2();
            }
            // 直接保存数据，不弹出弹框
            const res = await proxy.$vueAxios.post("Dynamic", {
              list: [newData],
              tableName: dynamicStore.visibleConfig.FMT.FMT_TableName
            });

            if (!res.Mark) {
              proxy.$message.error(`文件 ${fileName} 添加失败: ${res.Msg}`);
            } else {
              // 目录创建成功后，上传文件到新创建的目录
              await uploadFileToDirectory(file, newData);
            }
          }

          // 所有文件处理完成后刷新表格数据
          await getPageData();
          proxy.$message.success(`成功添加 ${files.length} 个文件`);
        } catch (error) {
          console.log(error);

          proxy.$message.error("文件添加过程中发生错误");
        } finally {
          proxy.$hideLoading();
        }
      }
    };

    const handleChildFileDrop = async (data: { files: File[]; columnType: string }) => {
      const { files, columnType } = data;
      if (columnType === "file") {
        // 检查子表新增权限 - 与 TopBar 中的 toggleDisabled 子表新增按钮逻辑保持一致
        let hasChildAddPermission = false;

        // 检查父表状态是否允许新增
        if (![1, 12].includes(dynamicStore.tableSelect[0]?.Status) && routeData.value.status === "Collect") {
          proxy.$message.warning("当前状态不允许新增");
          return;
        }

        // 检查当前子表的权限
        if (catalogStore.treeNode && catalogStore.treeNode.PC_PermissionStr) {
          hasChildAddPermission = childButtonList.value && childButtonList.value.includes("新增");
        }

        if (!hasChildAddPermission) {
          proxy.$message.warning("暂无上传权限");
          return;
        }

        // 处理子级表格文件拖拽
        const parentRecord = dynamicStore.tableSelect[0];
        if (!parentRecord) {
          proxy.$message.warning("请先选择父级数据");
          return;
        }

        // 显示加载状态
        proxy.$showLoading({ tip: `正在处理 ${files.length} 个文件...` });

        try {
          for (const file of files) {
            // 获取文件名（不包含扩展名）
            const fileName = file.name.replace(/\.[^/.]+$/, "");
            const currentYear = new Date().getFullYear();
            const currentCatalog = catalogStore.treeNode?.Catalog_ID || "";
            const stateNum: any = {
              Collect: 1,
              Arrangement: 2,
              Storage: 3,
              Utilization: 4
            };
            // 创建新数据对象
            const newData = {
              Order: "",
              SmallOrder: "",
              Year: currentYear,
              Title: fileName,
              Record_ID: global.createID(),
              PageCount: "",
              Parent_ID: parentRecord.Record_ID,
              Catalog_ID: dynamicStore.noCatalogStatus ? null : currentCatalog,
              Create_DateTime: new Date(),
              FMT_ID: childData.value[activeName.value]?.FMT_ID,
              FM_ID: routeData.value.fmid,
              Status: stateNum[routeData.value.status]
            };
            const ruleList = dynamicStore.childVisibleConfig.FieldRule.filter(
              (v: any) => v.FR_Enable === true || v.FR_Rule.toLowerCase().includes("jm")
            );
            const FieldRuleClass = new RuleClass({ modalFormData: newData, ruleList });
            const newModalFormData = FieldRuleClass.ReSetEncrypt();
            if (ruleList && ruleList.length && ruleList.length > 0) {
              const FieldRuleClass = new RuleClass({
                modalFormData: newModalFormData,
                ruleList,
                tableName: dynamicStore.childVisibleConfig.FMT.FMT_TableName
              }); // 执行字段规则类方法
              await FieldRuleClass.fieldRuleEvent2();
            }
            // 直接保存数据，不弹出弹框
            const res = await proxy.$vueAxios.post("Dynamic", {
              list: [newData],
              tableName: dynamicStore.childVisibleConfig.FMT.FMT_TableName
            });

            if (!res.Mark) {
              proxy.$message.error(`文件 ${fileName} 添加失败: ${res.Msg}`);
            } else {
              // 目录创建成功后，上传文件到新创建的目录
              await uploadFileToDirectory(file, newData);
            }
          }

          // 所有文件处理完成后刷新子表格数据
          await getChildTableData();
          proxy.$message.success(`成功添加 ${files.length} 个文件`);
        } catch (error) {
          proxy.$message.error("文件添加过程中发生错误");
        } finally {
          proxy.$hideLoading();
        }
      }
    };

    // 上传文件到指定目录的函数
    const uploadFileToDirectory = async (file: File, directoryData: any) => {
      try {
        const PieceSize = getSysConfig("PieceSize") ? getSysConfig("PieceSize") : 10;
        const lastFileTime = dtime(file.lastModified).format("YYYY-MM-DD HH:mm:ss");
        const filesize = file.size;
        const bytesPerPiece = 1024 * 1024 * PieceSize; // 每个文件切片大小
        const totalPieces = Math.ceil(filesize / bytesPerPiece);
        const AIID = global.createID();

        let start = 0;
        let progressIndex = 1;

        for (let uploadIndex = 1; uploadIndex <= totalPieces; uploadIndex++) {
          const end = Math.min(filesize, start + bytesPerPiece);
          const chunk = file.slice(start, end); // 切割文件

          const fileData = new FormData();
          fileData.append("file", chunk);
          fileData.append("AI_ID", AIID);
          fileData.append("PieceTotal", totalPieces.toString());
          fileData.append("PieceNow", uploadIndex.toString());
          fileData.append("AI_Name", file.name);
          fileData.append("AI_FileDateTime", lastFileTime);
          fileData.append("AI_Size", filesize.toString());
          fileData.append("AI_Index", "1"); // 默认索引
          fileData.append("FM_ID", directoryData.FM_ID);
          fileData.append("FMT_ID", directoryData.FMT_ID);
          fileData.append("Record_ID", directoryData.Record_ID);
          fileData.append("Catalog_ID", directoryData.Catalog_ID);

          const Res = await proxy.$vueAxios.post("MasterBaseAllInfos/Upload/Piece", fileData, { noLoading: true });

          if (!Res.Mark) {
            proxy.$message.warning(`文件上传错误: ${Res.Msg}`);
            return false;
          }

          start = start + chunk.size;
          progressIndex++;
        }

        proxy.$message.success(`文件 ${file.name} 上传成功`);
        return true;
      } catch (error) {
        console.error("文件上传失败:", error);
        proxy.$message.error(`文件 ${file.name} 上传失败`);
        return false;
      }
    };

    // 获取pinia数据
    const dynamicStore = useDynamicStore();
    // 当前组件实例
    const self = ref();
    // 获取全文组件实例
    const fulltextRef = ref();
    // 获取元数据实例
    const metaDataRef = ref();
    //表格实例
    const tabbarRef = ref();
    // 左侧树实例
    const leftTree = ref();
    // 子级数据集合
    const childData: any = ref([]);
    // 左侧树点击保存对象
    const leftTreeObj = ref();
    // 获取到所有的表数据
    const FMTData = ref<any[]>([]);

    // 四性检测弹框是否显示
    const fourAspectShow = ref<boolean>(false);
    // 是否展示四性检测记录
    const isShowFourAspectRecords = ref<boolean>(false);
    // 四性检测配置列表
    const fourAspectConfigs = ref<any[]>([]);
    // 四性检测点击行
    const fourAspectRow = ref<any>({});
    // 四性按钮点击查看记录
    const fourAspectRecordsClickRow = ref<any>({});
    // 四性检测dom
    const fourAspectRef = ref<any>({});
    // 当前四性检测的行
    const curFourAspectItem = ref<any>({});
    // 全部检测是否已经结束
    const allFinish = ref<boolean>(false);
    // 折叠面板活跃下标
    const activeIndex = ref<number>(1);
    // 是否停止检测
    const stopCheck = ref<boolean>(false);
    // 左侧splitpanes宽度比例
    const leftPaneSize = ref<number>(15);
    // 中间splitpanes宽度比例
    const middlePaneSize = ref<number>(50);

    // 表格配置
    const tableSetting = reactive({
      columns: [defaultVisibleColumn] as any[],
      rowClickObj: null as any, //点击保存行数据
      loading: false, //加载图标是否显示
      canClickNext: true, //下一页标识
      selectData: [] as any[],
      // 主表右键配置项
      tableMenu: {
        enabled: true,
        className: "my-menus",
        body: {
          options: [
            [
              { code: "dataInfo", name: "加入外链清单", prefixIcon: "DocumentAdd", className: "my-copy-item" },
              { code: "scanning", name: "四性检测" }
            ]
          ]
        }
      },
      // 工具栏配置
      toolbarConfig: {
        refresh: false as boolean | object,
        import: false as boolean | object,
        export: false as boolean | object,
        print: false as boolean | object,
        zoom: false as boolean | object,
        custom: false as boolean | object,
        slots: {
          buttons: "toolbarButtons"
        },
        enabled: true
      }
    });
    // 抽屉配置
    const drawerSetting = reactive({
      visible: false,
      title: ""
    });
    // 元数据弹框设置
    const metaDataSetting = reactive({
      visible: false
    });
    // 动态窗体配置
    const dynamicModal = reactive({
      title: "",
      htmlCode: "",
      type: "",
      formType: 1
    });
    // 移交下一环节配置
    const handoverSetting = reactive({
      visible: false, //是否显示窗体
      title: "", //窗体的标题
      data: [], //要提交的数据
      type: "", //标识是父级还是子级
      StatusValue: 1, // 流程状态
      openStatus: false // 数据是否是开放状态
    });
    // 移交下一环节弹框实例
    const HandOverModalRef = ref();
    // 批量挂接全文上传框实例
    const uploadZip = ref();
    // 全文批量挂接
    const uploadConfig = ref({
      visible: false,
      isCover: false
    });
    // 上传文件进度条配置
    const fulltextModal = reactive({
      isShow: false,
      percent: 0
    });
    // 监听当前页面状态
    const activatedFlag = ref(false);
    // 子级表格配置
    const childTableSetting = reactive({
      childTableData: [] as any[],
      // 子级表格头部按钮是否显示
      childTopBarShow: false,
      // 子级表格表头数据
      childColumns: defaultVisibleColumn as any[],
      // 子级表格加载状态
      childLoading: false,
      // 点击保存行数据
      rowClickObj: {} as any,
      // 选中数据
      selectData: [] as any[],
      // 子级表格下的子页面数据
      childDataByChildTable: [] as any[],
      // 子表右键配置项
      tableMenu: {
        enabled: true,
        className: "my-menus",
        body: {
          options: [
            [
              { code: "dataInfo", name: "加入外链清单", prefixIcon: "DocumentAdd", className: "my-copy-item" },
              { code: "scanning", name: "四性检测" }
            ]
          ]
        }
      },
      // 工具栏配置
      toolbarConfig: {
        refresh: false as boolean | object,
        import: false as boolean | object,
        export: false as boolean | object,
        print: false as boolean | object,
        zoom: false as boolean | object,
        custom: false as boolean | object,
        slots: {
          buttons: "toolbarButtons"
        },
        enabled: true
      }
    });
    // 子级表格实例
    const childTabbarRef = ref();
    // tab页标识
    const activeName = ref("0");
    // 主表报表数据
    const reportData = ref<any[]>([]);
    // 子表报表数据
    const childReportData = ref<any[]>([]);
    // 子表报表id
    const childReportIdData = ref<any[]>([]);
    // 离线挂接配置
    const mountSetting = reactive({
      visible: false,
      title: "离线挂接"
    });
    // 离线挂接表单绑定字段
    const formData = reactive({
      path: "",
      isCover: false,
      isOrder: true
    });
    // 离线挂接表单实例
    const mountForm = ref();
    // 离线挂载表单规则
    const mountRule = reactive({
      path: [{ required: true, message: "请填写路径", trigger: "change" }]
    });
    // 挂载配置
    const mountConfig = reactive({
      type: "folder"
    });
    // 粘贴配置
    const pasteSetting = reactive({
      visible: false,
      title: "选择粘贴参数",
      type: "",
      is_Copy: true
    });
    // 粘贴剪切表单绑定字段
    const pasteFormData = reactive({
      isTrue: true
    });
    // 删除弹框配置
    const singalrModal = reactive({
      visible: false, //弹框状态
      discontinueFont: "中止", // 弹框按钮文字
      discontinueStatus: false, // 弹框按钮状态
      networkStatus: true, // 单个网络状态
      AllNetworkStatus: true, // 所有的网络状态
      circulatingIndex: 0, // 循环索引
      percent: 0, // 进度条进度
      text: "" // 提示文字
    });
    // 重置流水号配置
    const resetLSH = reactive({
      visible: false,
      title: "重置流水号",
      type: 1
    });
    // 重置流水号表单绑定字段
    const resetLSHFormData = reactive({
      lsh_start: 1
    });
    // 重置流水号规则
    const LHSRule = reactive({
      lsh_start: [{ required: true, message: "请填写起始流水号", trigger: "blur" }]
    });
    // 流水号移至配置
    const LSHMoveSetting = reactive({
      visible: false,
      title: "流水号移至",
      type: ""
    });
    // 流水号移至表单绑定字段
    const LSHMoveFormData = ref({
      moveOrder: "1"
    });
    // 流水号表单实例
    const resetLHSRef = ref();
    // 标记备注弹框配置
    const remarkSetting = reactive({
      visible: false,
      title: "标记备注",
      type: ""
    });
    // 标记备注表单绑定字段
    const remarkFormData = reactive({
      remark: false,
      content: "",
      color: ""
    });
    // 标记备注表单实例
    const remarkForm = ref();
    // 数据查重弹框配置
    const dataCheckSetting = reactive({
      visible: false,
      title: "数据查重",
      type: ""
    });
    // 数据查重表单绑定字段
    const dataCheckFormData = reactive({
      field: []
    });
    // 数据查重表单实例
    const dataCheckForm = ref();
    // 数据查重表单规则
    const dataCheckRule = reactive({
      field: [{ required: true, message: "请选择字段", trigger: "change" }]
    });
    // 查找替换配置
    const ReplacementConfig = reactive({
      type: 1 // 用于区分是主表还是子表（1主表2子表）
    });
    // 查找替换弹框实例
    const replaceModal = ref();
    // 拆卷
    const dismantleSetting = reactive({
      visible: false,
      title: "拆卷",
      isTrue: false,
      type: "folder"
    });
    // 查询归卷
    const queryTheVolumeSetting = reactive({
      visible: false,
      title: "查询归卷"
    });
    // 查询归卷数据表绑定字段
    const queryTheVolumeSelect = ref<string>("");
    // 查询归卷表格配置
    const queryTheVolumeTableSetting = reactive({
      columns: [
        { type: "checkbox", width: 55 },
        // {
        //   title: "序号",
        //   field: "SmallOrder",
        //   width: 80
        // },
        { title: "年度", field: "Year", sortable: true, width: 65 },
        {
          title: "题名",
          field: "Title",
          sortable: true,
          formatter: formatter
        },
        {
          title: "责任者",
          field: "Responsibility",
          sortable: true,
          width: 120,
          formatter: formatter
        },
        {
          title: "文件日期",
          field: "FileDate",
          sortable: true,
          width: 120,
          formatter: formatter
        },
        {
          title: "文件编号",
          field: "FileNumber",
          sortable: true,
          width: 120
        },
        {
          title: "收文编号",
          field: "ReceiptCode",
          sortable: true,
          width: 120
        },
        {
          title: "流程实例ID",
          field: "WorkFlow_ID_InterFace",
          sortable: true,
          width: 120
        },
        {
          title: "创建时间",
          field: "Create_DateTime",
          sortable: true,
          width: 120
        },
        {
          title: "所属帐号",
          field: "Create_By",
          sortable: true,
          width: 120,
          formatter: ({ row, column, cellValue }: any) => {
            if (!cellValue) return "";
            const temp = userStore.getUserList.find((v: any) => v.U_ID === cellValue);
            return temp ? temp.U_CName : "";
          }
        }
      ],
      data: [] as any[],
      sourceData: [] as any[],
      selectData: [] as any[]
    });
    // 查询归卷搜索字段
    const queryTheVolumeInput = ref("");
    // 查询归卷子表规则
    const queryTheVolumeRule = ref<any>({});
    // 表格单击索引
    const tableIndex = ref(0);
    // 流水号操作弹框配置
    const LSHSetting = reactive({
      visible: false,
      title: "大流水号操作",
      columns: [
        { title: "新流水号", type: "seq", width: 120 },
        { title: "原大流水号", field: "Order", width: 120, sortable: true },
        { title: "原小流水号", field: "SmallOrder", width: 120, sortable: true },
        { title: "档号", field: "Code", width: 180, sortable: true },
        { title: "保管期限", field: "RetentionPeriod", width: 90, sortable: true, formatter: formatter },
        {
          title: "题名",
          field: "Title",
          sortable: true,
          formatter: ({ row, column, cellValue }: { row: any; column: any; cellValue: any }) => {
            return ACrypto.getSS(cellValue);
          }
        }
      ],
      columns2: [
        { title: "新流水号", type: "seq", width: 120 },
        { title: "原大流水号", field: "Order", width: 120, sortable: true },
        { title: "原小流水号", field: "SmallOrder", width: 120, sortable: true },
        { title: "档号", field: "Code", width: 180, sortable: true },
        { title: "文件日期", field: "FileDate", width: 90, sortable: true, formatter: formatter },
        {
          title: "题名",
          field: "Title",
          sortable: true,
          formatter: ({ row, column, cellValue }: { row: any; column: any; cellValue: any }) => {
            return ACrypto.getSS(cellValue);
          }
        }
      ],
      data: [] as any[],
      startLSH: 1,
      endLSH: null as number | null,
      // 加载字体
      loadingText: "正在加载中...",
      loading: false,
      // 流水号弹框表格点击数据行索引
      LShTableIndex: 0,
      // 流水号弹框表格点击数据
      rowClickObj: null as any,
      // 按钮加载事件
      btnLoading: false,
      btnLoading2: false,
      btnLoading3: false,
      btnLoading4: false,
      // 1代表主表2代表子表
      type: 1,
      ruleList: [] as any[],
      tableName: "",
      orderType: "Order"
    });
    // 流水号表格实例
    const lshTable = ref();
    // 子表按钮集合
    const childButtonList = ref<any[]>([]);
    // 搜索弹框配置
    const searchSetting = reactive({
      visible: false,
      title: "搜索"
    });
    // 回收站按钮是否显示
    const recycleStatus = ref(false);
    // url借阅弹框配置
    const urlModal = reactive({
      isShow: false
    });
    // url借阅弹框实例
    const UrlBorrowRef = ref();
    // 回收站按钮状态
    const recycleBtnStatus = ref([true, true]);
    // 字段规则集合
    const searchRuleList = ref<any>([]);
    // 用户数据集合
    const userList = computed(() => {
      return userStore.userList;
    });
    // 合卷配置项
    const rollUpConfig = reactive({
      title: "",
      fmtData: [],
      htmlCode: "",
      modalFormData: ""
    });
    // 合卷弹框实例
    const RollUpForm = ref();
    // 设置标签弹框配置
    const LabelSetting = reactive({
      visible: false,
      title: "设置标签",
      labelName: ""
    });
    // 搜索标签弹框配置
    const LabelSearchSetting = reactive({
      visible: false,
      title: "搜索标签"
    });
    // 子级设置标签弹框配置
    const LabelSetting2 = reactive({
      visible: false,
      title: "设置标签",
      labelName: ""
    });
    // 子级搜索标签弹框配置
    const LabelSearchSetting2 = reactive({
      visible: false,
      title: "搜索标签"
    });
    // 标签选中状态数据
    const labelStatusData = ref<any[]>([]);
    // 子级标签选中状态数据
    const labelStatusData2 = ref<any[]>([]);
    // 存储每个标签的选中状态
    const selectedItems = ref(new Array(dictionary["labels"]?.length).fill(false));
    // 存储选中的标签ID数组
    const selectedLabelIds = ref<string[]>([]);
    // 子级存储每个标签的选中状态
    const selectedItems2 = ref(new Array(dictionary["labels"]?.length).fill(false));
    // 子级存储选中的标签ID数组
    const selectedLabelIds2 = ref<string[]>([]);
    // 计算属性：将标签数据按DDL_FatherID分组
    const groupedLabels = computed(() => {
      if (!dictionary["labels"]) return [];

      const groups: any[] = [];
      const parentItems = dictionary["labels"].filter((item: any) => item.DDL_FatherID === null);

      parentItems.forEach((parent: any) => {
        const children = dictionary["labels"].filter((item: any) => item.DDL_FatherID === parent.DDL_ID);
        groups.push({
          title: parent.DDL_Name,
          titleId: parent.DDL_ID,
          children: children
        });
      });

      return groups;
    });

    // 左侧split缩放
    const handleResize = (panes: any) => {
      leftPaneSize.value = Math.ceil(panes[0].size);
      mittBus.emit("splitpanesPosition", {
        p: "left",
        v: leftPaneSize.value
      });
    };

    // 中间split缩放
    const handleMiddleResize = (panes: any) => {
      middlePaneSize.value = Math.ceil(panes[0].size);
      mittBus.emit("splitpanesPosition", {
        p: "middle",
        v: middlePaneSize.value
      });
    };

    // 主表搜索事件
    const search = () => {
      let param: any = {};
      // 构建查询参数
      for (const key in formModel) {
        if (formModel[key]) {
          param[key] = formModel[key];
        }
      }
      const params = {
        ...param,
        PageIndex: 1,
        PageSize: dynamicStore.pageSize ? dynamicStore.pageSize : 1000,
        FMT_ID: routeData.value.fmtid,
        Status: routeData.value.status,
        FuzzyQuery: formModel.FuzzyQuery
      };
      proxy.$vueAxios.post("Dynamic/Search", params).then((res: any) => {
        if (res.Mark) {
          if (res.Count < dynamicStore.pageSize) {
            dynamicStore.isShowPage = false;
          } else {
            dynamicStore.isShowPage = true;
          }
          dynamicStore.setTableData(res.List);
          dynamicStore.childTableData = [];
        } else {
          dynamicStore.isShowPage = false;
          dynamicStore.setTableData([]);
        }
      });
    };
    // 切换搜索显示和隐藏
    const trigger = () => {
      tableSearch.value = !tableSearch.value;
      searchSetting.visible = true;
    };
    // 重置
    const reset = (formEl: FormInstance | undefined) => {
      if (!formEl) return;
      formEl.resetFields();
    };
    /**
     * @description 获取搜索字段
     * @param
     * @param
     * @returns
     */
    const getSearchField = () => {
      proxy.$vueAxios
        .post(
          "Master_Base_Data_Disp_Mstr/GetConditional",
          {
            order: "DDM_Order asc",
            dtoList: [{ fieldName: "FMT_ID", fieldValue: routeData.value.fmtid }]
          },
          { noLoading: true }
        )
        .then((res: any) => {
          const str = "DDM_Enable_Query_" + routeData.value.status;
          searchFieldData.value = res.List.filter((v: any) => {
            return v[str] === true;
          });
          searchFieldData.value.forEach((item: any) => {
            Reflect.set(formModel, item.Field_Name, null);
          });
        });
    };
    // 获取搜索字段类型
    const getSearchFieldType = () => {
      proxy.$vueAxios
        .get("Table/column/get", { tableName: dynamicStore.visibleConfig.FMT.FMT_TableName }, { noLoading: true })
        .then((res: any) => {
          const arr = dynamicStore.visibleConfig.FieldRule.filter(
            (v: any) => v.FR_RuleType === "display" && v.FR_Enable === true
          );
          searchRuleList.value = arr;
          for (let i = 0; i < searchRuleList.value.length; i++) {
            const item = searchRuleList.value[i];
            for (let j = 0; j < searchFieldData.value.length; j++) {
              const item2 = searchFieldData.value[j];
              if (item.FR_TableField === item2.Field_Name && item.FR_Rule.includes("dictionary")) {
                item2.FR_TableField = item.FR_Rule.split(":")[1];
              }
              if (item.FR_TableField === item2.Field_Name && item.FR_Rule.includes("userInfo")) {
                item2.FR_TableField2 = item.FR_Rule.split(":")[1];
              }
            }
          }
          for (let i = 0; i < res.List.length; i++) {
            const item = res.List[i];
            for (let j = 0; j < searchFieldData.value.length; j++) {
              const item2 = searchFieldData.value[j];
              if (item.DbColumnName === item2.Field_Name) {
                item2.DataType = item.DataType;
              }
            }
          }
          console.log(searchFieldData.value, userList.value, "0000000000");
        });
    };
    // 点击树节点
    const onTreeClick = (treeNode: any) => {
      // tableSetting.toolbarConfig.enabled = true;
      tableSetting.rowClickObj = null;
      dynamicStore.childTableData = [];
      dynamicStore.childSourthTableData = [];
      tableSetting.selectData = [];
      topBarShow.value = true;
      recycleStatus.value = false;
      headerHeight.value = 42;
      const el = document.querySelector(".vxe-grid--toolbar-wrapper") as any;
      // 改变按钮状态
      leftTreeObj.value = treeNode;
      if (treeNode.PC_PermissionStr) {
        const buttonaArr = JSON.parse(treeNode.PC_PermissionStr)[0];
        if (buttonaArr.length > 0) {
          if (globalStore.assemblySize === "default") {
            el.style.height = "47px";
          } else if (globalStore.assemblySize === "large") {
            el.style.height = "57px";
          } else if (globalStore.assemblySize === "small") {
            el.style.height = "37px";
          }
        } else {
          el.style.height = "0";
        }
        if (buttonaArr.includes("导入")) {
          tableSetting.toolbarConfig.import = {
            icon: "vxe-icon-cloud-upload"
          };
        } else {
          tableSetting.toolbarConfig.import = false;
        }
        if (buttonaArr.includes("导出")) {
          tableSetting.toolbarConfig.export = {
            icon: "vxe-icon-cloud-download"
          };
        } else {
          tableSetting.toolbarConfig.export = false;
        }
        if (buttonaArr.includes("打印")) {
          tableSetting.toolbarConfig.print = {
            icon: "vxe-icon-print"
          };
        } else {
          tableSetting.toolbarConfig.print = false;
        }
        if (buttonaArr.includes("刷新")) {
          tableSetting.toolbarConfig.refresh = {
            icon: "vxe-icon-refresh",
            iconLoading: "vxe-icon-refresh roll"
          };
        } else {
          tableSetting.toolbarConfig.refresh = false;
        }
        if (buttonaArr.includes("全屏")) {
          tableSetting.toolbarConfig.zoom = {
            iconIn: "vxe-icon-fullscreen",
            iconOut: "vxe-icon-minimize"
          };
        } else {
          tableSetting.toolbarConfig.zoom = false;
        }
        if (buttonaArr.includes("自定义列")) {
          tableSetting.toolbarConfig.custom = {
            icon: "vxe-icon-menu"
          };
        } else {
          tableSetting.toolbarConfig.custom = false;
        }
      }
      dynamicStore.setPageIndex(true);
      if (dynamicStore.noCatalogStatus) {
        noClassManage();
      } else {
        getPageData();
      }
      getReportData();
      if (fatherObj) {
        dynamicStore.setChildLeftClick(true);
      } else {
        dynamicStore.setChildLeftClick(false);
      }
    };
    const signalrEvent = () => {
      proxy.signalr.off("SendTest");
      proxy.signalr.on("SendTest", (res: any) => {
        proxy.$showLoading({ tip: res });
        if (res.trim().startsWith("start")) {
          // 传输开始
          proxy.$showLoading({ tip: res });
        }
        if (res.trim().startsWith("stop")) {
          // 传输结束
          proxy.$hideLoading();
        }
      });
      proxy.signalr.off("DownloadZip");
      proxy.signalr.on("DownloadZip", (res: any) => {
        proxy.$showLoading({ tip: res });
        if (res.trim().startsWith("开始")) {
          // 传输开始
          proxy.$showLoading({ tip: res });
        }
        if (res.trim().startsWith("结束")) {
          // 传输结束
          proxy.$hideLoading();
        }
      });
      proxy.signalr.off("SendExecuteContentPage");
      proxy.signalr.on("SendExecuteContentPage", (res: any) => {
        proxy.$showLoading({ tip: "档案正在ORC中,请稍候..." });
        if (res.trim().startsWith("start")) {
          // 传输开始
          // proxy.$showLoading({ tip: res });
          proxy.$showLoading({ tip: "档案开始ORC,请稍候..." });
        }
        if (res.trim().startsWith("stop")) {
          // 传输结束
          proxy.$hideLoading();
        }
      });
    };
    /**
     * @description 获取主表报表数据
     * @param
     * @param
     * @returns
     */
    const getReportData = () => {
      proxy.$vueAxios
        .post(
          "Master_Base_ReportModule/GetConditional",
          {
            order: "RM_Index asc",
            dtoList: [{ fieldName: "FMT_ID", fieldValue: routeData.value.fmtid }]
          },
          { noLoading: true }
        )
        .then((res: any) => {
          if (res.Mark) {
            const filterData = catalogStore.catalogList.filter((v: any) => v.Catalog_ID === catalogStore.treeNode.Catalog_ID)[0];
            const permission = filterData ? JSON.parse(filterData.PC_PermissionStr)[2] : [];
            reportData.value = res.List.filter((v: any) => v.RM_Enabled).filter((v: any) => permission.includes(v.RM_ID));
          }
        });
    };
    // 报表单击
    const reportExcel = (item: any) => {
      if (tableSetting.selectData.length == 0) {
        proxy.$message.warning("请选择数据");
        return;
      }
      if (item.RM_IsFront) {
        new Excel(
          item,
          tableSetting.selectData,
          fatherObj ? [{ ...fatherObj }] : null,
          childTableSetting.childTableData
        ).download();
      } else {
        new ButtonClick().reportModuleClickEvent(item.RM_ID, item, "folder");
      }
    };
    // 主表单击
    const rowClick = async ({ row, rowIndex }: any) => {
      // 验证 row 参数
      if (!row || typeof row !== "object") {
        console.warn("rowClick: 无效的行数据");
        return;
      }

      tableIndex.value = rowIndex;
      // 显示子表格头部按钮
      childTableSetting.childTopBarShow = true;
      childHeaderHeight.value = 42;
      tableSetting.rowClickObj = row;

      // 当前点击行 - 确保在所有情况下都设置
      dynamicStore.setCurrClickRow(row);
      recycleBtnStatus.value = [false, false];
      dynamicStore.childTableSelect = [];

      // 检查是否与当前选中行相同
      if (isEqual(row, dynamicStore.tableSelect[0])) {
        return;
      }

      tabbarRef.value.setCheckboxRow([row], true);
      tableSelect([row]);

      if (globalStore.showChild && childData.value.length > 0) {
        // 子级表格数据
        await getChildButtonPermission();
        await getChildTableData();
      }

      console.log(userStore.userInfo);
      proxy.$vueAxios.post("Master_Base_Log", {
        fonds_ID: row["Fonds_ID"],
        fM_ID: row["FM_ID"],
        fmT_ID: row["FMT_ID"],
        g_ID: 66,
        u_ID: userStore.userInfo.U_ID,
        log_ID: proxy.$global.createID(),
        log_Type: "查询",
        log_Content: JSON.stringify(userStore.userInfo.U_CName + "用户看了目录[" + row["Title"] + "]"),
        log_Time: new Date().toLocaleDateString(),
        log_IP: "",
        log_RecordID: row["Record_ID"],
        log_RecordTMTID: 0,
        log_ChangMark: "数据查看",
        log_IsHighRisk: false,
        log_Remark: ""
      });
    };
    // 主表双击
    const rowdblClick = ({ row }: any) => {
      let flag = false;
      const newPC_PermissionStr = JSON.parse(catalogStore.treeNode.PC_PermissionStr)[0];
      newPC_PermissionStr.forEach((v: any) => {
        if (v == "修改") {
          flag = true;
        }
      });
      console.log("(((((((((((((((((((())))))))))))))))))))", !userStore.userInfo.U_ReadOnly, flag, !row.IsLock);

      if (route.query.status === "Collect") {
        console.log(!userStore.userInfo.U_ReadOnly, flag, !row.IsLock, [1, 12].includes(Number(row.Status)));
        if (!userStore.userInfo.U_ReadOnly && flag && !row.IsLock && [1, 12].includes(Number(row.Status))) {
          new ButtonClick().ParentClickEvent("修改", proxy);
        }
      } else if (route.query.status === "Arrangement") {
        if (!userStore.userInfo.U_ReadOnly && flag && !row.IsLock && [2, 22].includes(Number(row.Status))) {
          new ButtonClick().ParentClickEvent("修改", proxy);
        }
      } else if (route.query.status === "Storage") {
        if (!userStore.userInfo.U_ReadOnly && flag && !row.IsLock && [3].includes(Number(row.Status))) {
          new ButtonClick().ParentClickEvent("修改", proxy);
        }
      } else if (route.query.status === "Utilization") {
      }

      // if (
      //   !userStore.userInfo.U_ReadOnly &&
      //   flag &&
      //   !row.IsLock &&
      //   ![11, 21].includes(row.Status) &&
      //   route.query.status === "Collect" &&
      //   row.Status === 3
      // ) {
      //   new ButtonClick().ParentClickEvent("修改", proxy);
      // }
    };
    /**
     * @description: 主表右键单击
     */
    const menuClick = async ({ menu, row, column }: any) => {
      if (!row) {
        proxy.$message.warning("请选中数据!");
        return;
      }
      if (menu.code === "dataInfo") {
        const childFmt = FMTData.value.filter((v: any) => v.FMT_Parent_ID == row.FMT_ID);
        // 当前行下所有子表的全文
        await GetChildDataLists(childFmt, row.Record_ID);
        // 当前行全文
        await getFullTextData(row);
        urlModal.isShow = true;
        nextTick(() => {
          if (UrlBorrowRef.value) {
            UrlBorrowRef.value.open();
          }
        });
      }
      if (menu.code === "scanning") {
        console.log("row", row);
        fourAspectShow.value = true;
        allFinish.value = false; // 检测即置为扫描中
      }
    };
    const GetChildDataLists = async (ChildFmts: any, ParentID: string) => {
      for (let i = 0; i < ChildFmts.length; i++) {
        const fmt = ChildFmts[i];
        await proxy.$vueAxios
          .get(
            "Dynamic/CommonGet",
            {
              fmtid: fmt.FMT_ID,
              parentid: ParentID,
              fmid: routeData.value.fmid,
              status: routeData.value.status,
              isDelete: false,
              searchType: 2
            },
            { noLoading: true }
          )
          .then(async (res: any) => {
            for (let j = 0; j < res.List.length; j++) {
              const item = res.List[j];
              await doUrl(item);
              await GetChildDataLists(
                FMTData.value.filter((v: any) => v.FMT_Parent_ID == fmt.FMT_ID),
                item.Record_ID
              );
            }
          });
      }
    };
    const doUrl = (dataRow: any) => {
      proxy.$vueAxios
        .post(
          "Master_Base_AllInfos/GetConditional",
          {
            order: "AI_Index asc",
            dtoList: [{ fieldName: "Record_ID", fieldValue: dataRow.Record_ID }]
          },
          { noLoading: true }
        )
        .then((res: any) => {
          appStore.setBorrrowData(res.List);
        });
    };
    // 点击右键获取全文数据
    const getFullTextData = async (row: any) => {
      await proxy.$vueAxios
        .post(
          "Master_Base_AllInfos/GetConditional",
          {
            order: "AI_Index asc",
            dtoList: [{ fieldName: "Record_ID", fieldValue: row.Record_ID }]
          },
          { noLoading: true }
        )
        .then((res: any) => {
          // tableSetting.data = res.List;
          appStore.setBorrrowData(res.List);
        });
    };
    // 停止检测
    const stopCheckHandle = () => {
      stopCheck.value = true; // 停止检测
    };
    // 开始检测
    const seletedDataHandle = async () => {
      stopCheck.value = false; // 开始检测
      console.log("selectedData", tableSetting.selectData);
      const allSelectedData = [...tableSetting.selectData, ...childTableSetting.selectData];
      if (!allSelectedData.length) {
        proxy.$message.warning("请确保勾选了数据!");
        fourAspectShow.value = false;
        return;
      }
      for (let index = 0; index < allSelectedData.length; index++) {
        try {
          if (stopCheck.value) {
            proxy.$message.warning("已停止四性检测!");
            return;
          }
          const config = allSelectedData[index];
          fourAspectRow.value = config;

          const res = await proxy.$vueAxios.post("Master_Base_FourAspect_Conf/GetConditional", {
            pageIndex: 0,
            pageSize: 0,
            order: "table_id asc",
            dtoList: [
              {
                fieldName: "table_id",
                fieldValue: config.FMT_ID,
                conditionalType: 0
              }
            ]
          });

          if (res.Mark) {
            if (res.List.length) {
              fourAspectConfigs.value = res.List;

              curFourAspectItem.value = allSelectedData[index]; // 传入归档号及标题
              curFourAspectItem.value.Title = ACrypto.getSS(curFourAspectItem.value.Title);

              await new Promise(r => {
                setTimeout(() => {
                  r(1);
                }, 1000);
              });

              activeIndex.value = index + 1;
              await fourAspectRef.value?.checkHandle();
              if (stopCheck.value) {
                proxy.$message.warning("已停止四性检测!");
                return;
              }
              // 检测完毕之后提示
              if (index >= allSelectedData.length - 1) {
                allFinish.value = true; // 检测完毕
                fourAspectRef.value?.pauseTimer();
                proxy.$message.success("检测完毕！");
              }
            } else {
              fourAspectShow.value = false; // 没有配置项则关闭弹框
              proxy.$message.warning(`归档号${config.Code}未配置四性检测策略!`);
            }
          }
        } catch (error) {
          console.log(error);
        }
      }

      // proxy.$vueAxios
      //   .post("Master_Base_FourAspect_Conf/GetConditional", {
      //     pageIndex: 0,
      //     pageSize: 0,
      //     order: "table_id asc",
      //     dtoList: [
      //       {
      //         fieldName: "table_id",
      //         fieldValue: item.FMT_ID,
      //         conditionalType: 0
      //       }
      //     ]
      //   })
      //   .then((res: any) => {
      //     console.log("四性检测配置查询---", res);
      //     if (res.Mark) {
      //       if (res.List.length) {
      //         fourAspectConfigs.value = res.List;
      //         fourAspectShow.value = true;
      //       } else {
      //         proxy.$message.warning("请先导入检测配置数据!");
      //       }
      //     }
      //   });
    };
    // 主表多选
    const tableSelect = (val: any) => {
      tableSetting.selectData = val;
      dynamicStore.setTableSelect(val);
      console.log(tableSetting.selectData);

      if (tableSetting.selectData.length > 0) {
        recycleBtnStatus.value = [false, false];
      } else {
        recycleBtnStatus.value = [true, true];
      }
    };
    /**
     * @description 主表跳转子级页面
     * @param
     * @param
     * @returns
     */
    const toSublevel = async (row: any, item: any) => {
      const Res = await proxy.$vueAxios.post("Master_Base_FormModel_Table/GetConditional", {
        order: "FMT_Type ASC",
        dtoList: [
          {
            fieldName: "FM_ID",
            fieldValue: routeData.value.fmid
          }
        ]
      });
      const childrenFmtId2 = Res.List.filter((v: any) => v.FMT_Parent_ID === item.FMT_ID).map((v: any) => v.FMT_ID);
      // const stateName: any = {
      //   1: "Collect",
      //   2: "Arrangement",
      //   3: "Storage",
      //   4: "Utilization"
      // };
      router.push({
        name: "sublevel",
        query: {
          fmid: row.FM_ID,
          fmtid: item.FMT_ID,
          childrenFmtId: childrenFmtId2,
          status: routeData.value.status,
          fondsId: routeData.value.fondsId,
          code: row.Code,
          fatherObj: encodeURIComponent(JSON.stringify(row))
        }
      });
    };
    /**
     * @description 主表查看全文
     * @param
     * @param
     * @returns
     */
    const viewFullText = (row: any) => {
      drawerSetting.title = "查看全文";
      drawerSetting.visible = true;
      nextTick(() => {
        fulltextRef.value.getData(row);
      });

      buttonStatus.filterFulltextButtonAuth(JSON.parse(catalogStore.treeNode.PC_PermissionStr)[1]);
    };
    /**
     * @description 获取表格数据
     * @param
     * @param
     * @returns
     */
    const getPageData = async () => {
      if (leftTreeObj.value || routeData.value.fatherObj) {
        tableSetting.loading = true;
        dynamicStore
          .getTableData({
            fmid: routeData.value.fmid,
            fmtid: routeData.value.fmtid,
            catalogid: leftTreeObj.value ? leftTreeObj.value.Catalog_ID : null,
            status: routeData.value.status,
            searchType: leftTreeObj.value ? 1 : 2,
            pageIndex: 1,
            pageSize: dynamicStore.pageSize ? dynamicStore.pageSize : 0,
            parentid: routeData.value.fatherObj
              ? JSON.parse(decodeURIComponent(routeData.value.fatherObj as any)).Record_ID
              : undefined
          })
          .then((res: any) => {
            tableSetting.loading = false;
            dynamicStore.setTableData(res.List);
            dynamicStore.setSourthTableData(res.List);
            if (tableSetting.selectData.length > 0) {
              tableSetting.selectData.forEach(element => {
                if (dynamicStore.tableData.filter(s => s.Record_ID === element.Record_ID).length > 0) {
                  dynamicStore.tableData.filter(s => s.Record_ID === element.Record_ID)[0].checkbox = true;
                }
              });
            }
          })
          .catch(() => {
            tableSetting.loading = false;
          });
        console.log("#########################");
      } else {
        dynamicStore.setTableData([]);
      }
    };
    // 无分类管理
    const noClassManage = () => {
      dynamicStore.setChildLeftClick(false);
      headerHeight.value = 42;
      const el = document.querySelector(".vxe-grid--toolbar-wrapper") as any;
      if (globalStore.assemblySize === "default") {
        el.style.height = "47px";
      } else if (globalStore.assemblySize === "large") {
        el.style.height = "57px";
      } else if (globalStore.assemblySize === "small") {
        el.style.height = "37px";
      }
      if (dynamicStore.noCatalogStatus) {
        topBarShow.value = true;
        recycleStatus.value = false;
        tableSetting.loading = true;
        dynamicStore.childTableData = [];
        dynamicStore
          .getTableData({
            fmid: routeData.value.fmid,
            fmtid: routeData.value.fmtid,
            status: routeData.value.status,
            searchType: dynamicStore.noCatalogStatus ? 1 : 2,
            pageIndex: 1,
            pageSize: dynamicStore.pageSize ? dynamicStore.pageSize : 0
            // parentid: routeData.value.fatherObj
            //   ? JSON.parse(decodeURIComponent(routeData.value.fatherObj as any)).Record_ID
            //   : undefined
          })
          .then((res: any) => {
            tableSetting.loading = false;
            dynamicStore.setTableData(res.List);
            dynamicStore.setSourthTableData(res.List);
            if (tableSetting.selectData.length > 0) {
              tableSetting.selectData.forEach(element => {
                if (dynamicStore.tableData.filter(s => s.Record_ID === element.Record_ID).length > 0) {
                  dynamicStore.tableData.filter(s => s.Record_ID === element.Record_ID)[0].checkbox = true;
                }
              });
            }
          })
          .catch(() => {
            tableSetting.loading = false;
          });
      } else {
        getPageData();
      }
    };
    /**
     * @description 主表按钮点击事件
     * @param
     * @param
     * @returns
     */
    const buttonClick = (name: string) => {
      new ButtonClick().ParentClickEvent(name, proxy);
    };
    /**
     * @description 获取表头数据
     * @param
     * @param
     * @returns
     */
    const getColumns = async () => {
      await proxy.$vueAxios.get("MasterBaseFormModelTable/GetInitialize", { fmtId: routeData.value.fmtid }).then((res: any) => {
        dynamicStore.setVisibleConfig(res.List[0]);
        const str = "DDM_Enable_Display_" + routeData.value.status;
        const filterColumns = res.List[0].DDMList.filter((v: any) => v[str] === true).sort((a: any, b: any) => {
          return a.DDM_Order - b.DDM_Order;
        });
        tableSetting.columns = filterColumns;
      });
    };
    /**
     * @description 获取当前数据下的子级
     * @param
     * @param
     * @returns
     */
    const getChild = () => {
      proxy.$vueAxios
        .get(
          "MasterPermission/GetUserPermissionFMT",
          {
            fmId: routeData.value.fmid,
            status: routeData.value.status
          },
          {
            noLoading: true
          }
        )
        .then((res: any) => {
          FMTData.value = res.List;
          childData.value = res.List.filter((v: any) => v.FMT_Enable && v.FMT_Parent_ID === routeData.value.fmtid);
          dynamicStore.setChildData(childData.value);

          // 获取数据之后进行定位
          const status = route.query.status;
          const fmtid = route.query.fmtid;
          const middlePaneSizeKey = `middle_${status}_${fmtid}`;
          middlePaneSize.value = globalStore.splitpanesPos[middlePaneSizeKey] ?? 50;
        });
    };
    /**
     * @description 获取子级页面按钮权限
     * @param
     * @param
     * @returns
     */
    const getChildBtnPermission = () => {
      const filterData = catalogStore.catalogList.filter((v: any) => v.Catalog_ID === catalogStore.treeNode.Catalog_ID)[0];
      filterData ? buttonStatus.filterButtonAuth(JSON.parse(filterData.PC_PermissionStr)[0]) : buttonStatus.filterButtonAuth([]);
    };
    /**
     * @description 获取搜索功能分类数据
     * @param
     * @param
     * @returns
     */
    const getCatalog = () => {
      proxy.$vueAxios
        .get("MasterPermission/GetUserPermissionCatalog", {
          fmtId: route.query.fmtid,
          status: route.query.status
        })
        .then((res: any) => {
          catalogList.value = res.List;
        });
    };
    // 下一页
    const pageNext = () => {
      if (tableSetting.canClickNext) {
        tableSetting.canClickNext = false;
        tableSetting.loading = true;
        dynamicStore
          .getTableData({
            fmid: routeData.value.fmid,
            fmtid: routeData.value.fmtid,
            catalogid: dynamicStore.noCatalogStatus ? undefined : catalogStore.treeNode.Catalog_ID,
            status: routeData.value.status,
            searchType: 1,
            pageIndex: dynamicStore.pageIndex,
            pageSize: dynamicStore.pageSize ? dynamicStore.pageSize : 0
          })
          .then((res: any) => {
            tableSetting.loading = false;
            dynamicStore.setPageIndex();
            if (res.Count <= dynamicStore.pageIndex * dynamicStore.pageSize || res.List.length === 0) {
              dynamicStore.setPageIndex(true); //重置pageIndex为2
            }
            tableSetting.canClickNext = true;
            const data = dynamicStore.tableData;
            const datas = data.concat(res.List);
            if (res.Count <= datas.length) {
              dynamicStore.setIsShowPage(false);
            }
            dynamicStore.setTableData(datas);
          })
          .catch(() => {
            tableSetting.loading = false;
          });
      }
    };
    // 全部数据
    const pageAll = () => {
      if (tableSetting.canClickNext) {
        tableSetting.canClickNext = false;
        tableSetting.loading = true;
        dynamicStore
          .getTableData({
            fmid: routeData.value.fmid,
            fmtid: routeData.value.fmtid,
            catalogid: dynamicStore.noCatalogStatus ? undefined : catalogStore.treeNode.Catalog_ID,
            status: routeData.value.status,
            searchType: 1
          })
          .then((res: any) => {
            tableSetting.canClickNext = true;
            dynamicStore.setTableData(res.List);
            tableSetting.loading = false;
          })
          .catch(() => {
            tableSetting.loading = false;
          });
      }
    };
    // excel导入文件
    const exportExcel = async (files: any) => {
      await new ButtonClick().ExportExcel(files, proxy);
    };
    // 批量挂接全文配置参数
    const fulltextUploadMany = () => {
      uploadZip.value.click();
      uploadConfig.value.visible = false;
    };
    // 批量挂接全文触发事件
    const uploadZipFile = async () => {
      await new ButtonClick().uploadZipEvent(uploadZip.value.files, proxy);
      uploadZip.value.value = null;
    };
    const initPaneSize = () => {
      const status = route.query.status;
      const fmtid = route.query.fmtid;
      const leftPaneSizeKey = `left_${status}_${fmtid}`;
      leftPaneSize.value = globalStore.splitpanesPos[leftPaneSizeKey] ?? 15;
    };
    // 页面初始化
    const init = async () => {
      initPaneSize();
      // leftTree.value.getTreeData();
      dynamicStore.setChildLeftClick(false);
      dynamicStore.setNoCatalog(false);
      getCatalog();
      await getColumns();
      dynamicStore.setFatherObj(fatherObj);
      self.value = proxy;
      getChild();
      getSearchField();
      getSearchFieldType();
      if (fatherObj) {
        topBarShow.value = true;
        const el = document.querySelector(".vxe-grid--toolbar-wrapper") as any;
        const buttonaArr = JSON.parse(catalogStore.treeNode.PC_PermissionStr)[0];
        if (buttonaArr.length > 0) {
          if (globalStore.assemblySize === "default") {
            el.style.height = "47px";
          } else if (globalStore.assemblySize === "large") {
            el.style.height = "57px";
          } else if (globalStore.assemblySize === "small") {
            el.style.height = "37px";
          }
        } else {
          el.style.height = "0";
        }
        getChildBtnPermission();
        getReportData();
      }
      getPageData();
    };
    onActivated(async () => {
      init();
      dynamicStore.setChildLeftClick(false);
      // dynamicStore.childTableData = [];
      if (tableSetting.rowClickObj && childData.value.length > 0) {
        await getChildButtonPermission();
        await getChildTableData();
      }

      if (leftTreeObj.value) {
        buttonStatus.filterButtonAuth(JSON.parse(leftTreeObj.value.PC_PermissionStr)[0]);
        // dynamicStore.setChildLeftClick(true);
      } else {
        // dynamicStore.setChildLeftClick(false);
      }
    });
    onDeactivated(() => {
      if (fatherObj) {
        leftTreeObj.value = null;
        console.log(leftTree.value.ztreeObj);
        console.log(leftTree.value);

        dynamicStore.setChildLeftClick(false);
        leftTree.value.clearTreeNodeSelect();
      }

      dynamicStore.tableData = [];
      dynamicStore.childTableData = [];
    });
    /**
     * @description 获取子表数据
     * @param
     * @param
     * @returns
     */
    // tab页切换事件
    const tabChange = async (val: any) => {
      console.log(val);

      if (tableSetting.rowClickObj) {
        activeName.value = val;
        // 改变按钮状态
        await getChildButtonPermission();
        await getChildTableData();
      } else {
        childTabbarRef.value[activeName.value].reloadData([]);
      }
    };
    // 获取子级表格数据
    const getChildTableData = async () => {
      if (globalStore.showChild && childData.value.length > 0) {
        childTableSetting.childLoading = true;
        try {
          // 获取子表表头数据

          const childColumnsRes = await proxy.$vueAxios.get(
            "MasterBaseFormModelTable/GetInitialize",
            {
              fmtId: childData.value[activeName.value] ? childData.value[activeName.value].FMT_ID : null
            },
            { noLoading: true }
          );
          if (childColumnsRes.Mark) {
            dynamicStore.setChildVisibleConfig(childColumnsRes.List[0]);
            const str = "DDM_Enable_Display_" + routeData.value.status;
            const filterColumns = childColumnsRes.List[0].DDMList.filter((v: any) => v[str] === true).sort((a: any, b: any) => {
              return a.DDM_Order - b.DDM_Order;
            });
            childTableSetting.childColumns = filterColumns;
          }
          // 获取子表数据
          const childTableRes = await proxy.$vueAxios.get(
            "Dynamic/CommonChildTableGet",
            {
              fmid: tableSetting.rowClickObj.FM_ID,
              dataId: tableSetting.rowClickObj.Record_ID,
              fmtType: childData.value[activeName.value].FMT_Type
            },
            { noLoading: true }
          );
          if (childTableRes.Mark) {
            childTableSetting.childTableData = childTableRes.List;
            childTableSetting.childLoading = false;
            dynamicStore.setChildTableData(childTableRes.List);
            dynamicStore.setChildSourthTableData(childTableRes.List);
          }
          await getChildDataByChildTable();
          getChildReportData();
        } catch (error) {
          childTableSetting.childLoading = false;
        } finally {
          childTableSetting.childLoading = false;
        }
      }
    };

    // 子表单击
    const childRowClick = ({ row }: any) => {
      childTabbarRef.value[activeName.value].setCheckboxRow([row], true);
      childTableSetting.rowClickObj = row;
      childTableSelect([row]);
    };
    // 子表双击
    const childRowdblClick = ({ row }: any) => {
      // 判断是否可双击打开弹框
      // if (!userStore.userInfo.U_ReadOnly && childButtonList.value.includes("修改") && ![11, 21].includes(row.Status)) {
      //   new ButtonClick().ChildClickEvent("修改", proxy);
      // }
      if (route.query.status === "Collect") {
        if (
          !userStore.userInfo.U_ReadOnly &&
          childButtonList.value.includes("修改") &&
          !row.IsLock &&
          [1, 12].includes(Number(row.Status))
        ) {
          new ButtonClick().ChildClickEvent("修改", proxy);
        }
      } else if (route.query.status === "Arrangement") {
        if (
          !userStore.userInfo.U_ReadOnly &&
          childButtonList.value.includes("修改") &&
          !row.IsLock &&
          [2, 22].includes(Number(row.Status))
        ) {
          new ButtonClick().ChildClickEvent("修改", proxy);
        }
      } else if (route.query.status === "Storage") {
        if (
          !userStore.userInfo.U_ReadOnly &&
          childButtonList.value.includes("修改") &&
          !row.IsLock &&
          [3].includes(Number(row.Status))
        ) {
          new ButtonClick().ChildClickEvent("修改", proxy);
        }
      } else if (route.query.status === "Utilization") {
      }
    };
    // 子表多选
    const childTableSelect = (val: any[]) => {
      childTableSetting.selectData = val;
      dynamicStore.setChildTableSelect(val);
    };
    // 获取子表报表数据
    const getChildReportData = () => {
      proxy.$vueAxios
        .post(
          "Master_Base_ReportModule/GetConditional",
          {
            order: "RM_Index asc",
            dtoList: [{ fieldName: "FMT_ID", fieldValue: childData.value[activeName.value].FMT_ID }]
          },
          { noLoading: true }
        )
        .then((res: any) => {
          if (res.Mark) {
            console.log(childReportIdData.value, 3333333333333333);
            childReportData.value = res.List.filter((v: any) => v.RM_Enabled).filter((v: any) =>
              childReportIdData.value.includes(v.RM_ID)
            );
          }
        });
    };
    /**
     * @description 获取子级表格中的按钮权限
     * @param
     * @param
     * @returns
     */
    const getChildButtonPermission = async () => {
      await proxy.$vueAxios
        .get(
          "MasterPermission/GetArchivesChildButtonPermission",
          {
            fmtId: childData.value[activeName.value].FMT_ID,
            status: routeData.value.status,
            catalogId: tableSetting.rowClickObj.Catalog_ID
          },
          {
            noLoading: true
          }
        )
        .then((res: any) => {
          const el = document.querySelectorAll(".vxe-grid--toolbar-wrapper") as any;
          if (res.Model) {
            childButtonList.value = JSON.parse(res.Model)[0];
            buttonStatus.filterChildButtonAuth(JSON.parse(res.Model)[0]);
            childReportIdData.value = JSON.parse(res.Model)[2];

            const buttonaArr = JSON.parse(res.Model)[0];
            if (buttonaArr.length > 0) {
              if (globalStore.assemblySize === "default") {
                el[Number(activeName.value) + 1].style.height = "47px";
              } else if (globalStore.assemblySize === "large") {
                el[Number(activeName.value) + 1].style.height = "57px";
              } else if (globalStore.assemblySize === "small") {
                el[Number(activeName.value) + 1].style.height = "37px";
              }
            } else {
              el[Number(activeName.value) + 1].style.height = "0";
            }
            if (buttonaArr.includes("导入")) {
              childTableSetting.toolbarConfig.import = {
                icon: "vxe-icon-cloud-upload"
              };
            } else {
              childTableSetting.toolbarConfig.import = false;
            }
            if (buttonaArr.includes("导出")) {
              childTableSetting.toolbarConfig.export = {
                icon: "vxe-icon-cloud-download"
              };
            } else {
              childTableSetting.toolbarConfig.export = false;
            }
            if (buttonaArr.includes("打印")) {
              childTableSetting.toolbarConfig.print = {
                icon: "vxe-icon-print"
              };
            } else {
              childTableSetting.toolbarConfig.print = false;
            }
            if (buttonaArr.includes("刷新")) {
              childTableSetting.toolbarConfig.refresh = {
                icon: "vxe-icon-refresh",
                iconLoading: "vxe-icon-refresh roll"
              };
            } else {
              childTableSetting.toolbarConfig.refresh = false;
            }
            if (buttonaArr.includes("全屏")) {
              childTableSetting.toolbarConfig.zoom = {
                iconIn: "vxe-icon-fullscreen",
                iconOut: "vxe-icon-minimize"
              };
            } else {
              childTableSetting.toolbarConfig.zoom = false;
            }
            if (buttonaArr.includes("自定义列")) {
              childTableSetting.toolbarConfig.custom = {
                icon: "vxe-icon-menu"
              };
            } else {
              childTableSetting.toolbarConfig.custom = false;
            }
            childTableSetting.toolbarConfig.enabled = true;
          } else {
            if (el.style) {
              el.style.height = "0";
            }
            buttonStatus.filterChildButtonAuth([]);
          }
        });
    };
    /**
     * @description 获取当前子级表格数据下的子级
     * @param
     * @param
     * @returns
     */
    const getChildDataByChildTable = async () => {
      await proxy.$vueAxios
        .post(
          "Master_Base_FormModel_Table/GetConditional",
          {
            order: "FMT_Type ASC",
            dtoList: [
              {
                fieldName: "FM_ID",
                fieldValue: routeData.value.fmid
              }
            ]
          },
          {
            noLoading: true
          }
        )
        .then((res: any) => {
          childTableSetting.childDataByChildTable = res.List.filter(
            (v: any) => v.FMT_Parent_ID === childData.value[activeName.value].FMT_ID
          );
        });
    };
    // 子表跳转子级页面
    const childToSublevel = async (row: any, item: any) => {
      const Res = await proxy.$vueAxios.post("Master_Base_FormModel_Table/GetConditional", {
        order: "FMT_Type ASC",
        dtoList: [
          {
            fieldName: "FM_ID",
            fieldValue: routeData.value.fmid
          }
        ]
      });
      const childrenFmtId2 = Res.List.filter((v: any) => v.FMT_Parent_ID === row.FMT_ID).map((v: any) => v.FMT_ID);
      // const stateName: any = {
      //   1: "Collect",
      //   2: "Arrangement",
      //   3: "Storage",
      //   4: "Utilization"
      // };
      router.push({
        name: "sublevel",
        query: {
          fmid: row.FM_ID,
          fmtid: item.FMT_ID,
          childrenFmtId: childrenFmtId2,
          status: routeData.value.status,
          fondsId: routeData.value.fondsId,
          code: row.Code,
          fatherObj: encodeURIComponent(JSON.stringify(row))
        }
      });
    };
    // 子表查看全文
    const childViewFullText = (row: any) => {
      drawerSetting.title = "全文管理";
      drawerSetting.visible = true;
      nextTick(() => {
        console.log(fulltextRef.value);

        fulltextRef.value.getData(row);
      });
      buttonStatus.filterFulltextButtonAuth(JSON.parse(catalogStore.treeNode.PC_PermissionStr)[1]);
    };
    // 子级表格按钮点击事件
    const childButtonClick = (name: string) => {
      new ButtonClick().ChildClickEvent(name, proxy);
    };
    // 子级表格报表导出
    const childReportExcel = (item: any) => {
      if (childTableSetting.selectData.length == 0) {
        proxy.$message.warning("请选择数据");
        return;
      }
      if (item.RM_IsFront) {
        new Excel(item, childTableSetting.selectData, [tableSetting.rowClickObj], []).download();
      } else {
        new ButtonClick().reportModuleClickEvent(item.RM_ID, item, "file");
      }
    };
    // 离线挂接提交按钮
    const mountHandle = () => {
      const { tableSelect, childTableSelect } = dynamicStore;
      mountForm.value.validate(async (valid: boolean) => {
        if (valid) {
          const errorList: any = [];
          if (mountConfig.type === "folder") {
            mountSetting.visible = false;
            for (let i = 0; i < tableSelect.length; i++) {
              proxy.$showLoading({ tip: `正在挂载第${i + 1}条数据,档号为${tableSelect[i].Code}` });
              const param = {
                path: formData.path,
                isCover: formData.isCover,
                isOrder: formData.isOrder,
                fmT_ID: tableSelect[0].FMT_ID,
                fM_ID: tableSelect[0].FM_ID,
                idList: [tableSelect[i].Record_ID]
              };
              const Res = await proxy.$vueAxios.post("MasterBaseAllInfos/MatchingAllInfo", param, { noLoading: true });
              if (!Res.Mark) {
                errorList.push([Res.Msg]);
              }
            }
            proxy.$hideLoading();
          } else if (mountConfig.type === "file") {
            mountSetting.visible = false;
            for (let i = 0; i < childTableSelect.length; i++) {
              proxy.$showLoading({ tip: `正在挂载第${i + 1}条数据,档号为${childTableSelect[i].Code}` });
              const param = {
                path: formData.path,
                isCover: formData.isCover,
                fmT_ID: childTableSelect[0].FMT_ID,
                fM_ID: childTableSelect[0].FM_ID,
                idList: [childTableSelect[i].Record_ID]
              };
              const Res = await proxy.$vueAxios.post("MasterBaseAllInfos/MatchingAllInfo", param, { noLoading: true });
              if (!Res.Mark) {
                errorList.push([Res.Msg]);
              }
            }
            proxy.$hideLoading();
          }
          if (errorList.length > 0) {
            import("@/vendor/Export2Excel").then(excel => {
              excel.export_json_to_excel({
                // 要求转出的表头是中文
                header: ["错误信息"], // 表头 必填
                data: errorList, // //具体数据 必填
                filename: "离线挂载错误信息", // 非必填
                autoWidth: true, // 非必填
                bookType: "xlsx" // 非必填
              });
            });
          }
        }
      });
    };
    // 粘贴剪切弹框确认事件
    const pasteHandle = async () => {
      const { visibleConfig, childVisibleConfig, copyData, copyChildData } = dynamicStore;

      const stateNum: any = {
        Collect: 1,
        Arrangement: 2,
        Storage: 3,
        Utilization: 4
      };
      // 剪贴板为空则禁止
      const itemsRaw = pasteSetting.type === "folder" ? copyData : copyChildData;
      if (!itemsRaw || itemsRaw.length === 0) {
        proxy.$message.warning("剪贴板为空，请先复制/剪贴数据");
        return;
      }
      // 去重（按 Record_ID）
      const seen = new Set<string | number>();
      const items = itemsRaw.filter((it: any) => {
        const id = it?.Record_ID;
        if (seen.has(id)) return false;
        seen.add(id);
        return true;
      });

      const errList: string[] = [];

      // 并发控制
      let maxConcurrency = Number(globalStore.pasteConcurrency || 4);
      const currentRules = pasteSetting.type === "folder" ? visibleConfig.FieldRule || [] : childVisibleConfig.FieldRule || [];
      const hasOrderTrigger = currentRules.some(
        (v: any) =>
          v.FR_Enable === true && v.FR_RuleType === "trigger" && (v.FR_TableField === "Order" || v.FR_TableField === "SmallOrder")
      );
      if (hasOrderTrigger) {
        maxConcurrency = 1; // 顺序敏感时，强制串行以保证 Order/SmallOrder 正确
      }
      const pending: Promise<void>[] = [];
      let completed = 0;

      // 关闭粘贴弹框，打开进度弹框
      pasteSetting.visible = false;
      singalrModal.visible = true;
      singalrModal.AllNetworkStatus = true;
      singalrModal.networkStatus = true;
      singalrModal.circulatingIndex = 0;
      singalrModal.percent = 0;

      const makeParam = (it: any) =>
        pasteSetting.type === "folder"
          ? {
              fromFMID: it.FM_ID,
              fromFMTID: it.FMT_ID,
              fromTableID: it.Record_ID,
              fromCatalogID: it.Catalog_ID,
              toFMID: visibleConfig.FMT.FM_ID,
              toFMTID: visibleConfig.FMT.FMT_ID,
              fromFondsID: it.Fonds_ID,
              toFondsID: catalogStore.treeNode.Fonds_ID,
              toStatus: stateNum[routeData.value.status],
              toParentID: dynamicStore.childLeftClick ? null : fatherObj ? fatherObj.Record_ID : null,
              toCatalog_ID: dynamicStore.noCatalogStatus ? null : catalogStore.treeNode.Catalog_ID,
              is_Copy: pasteSetting.is_Copy,
              is_CopyJN: true,
              is_CopyAllInfo: pasteFormData.isTrue
            }
          : {
              fromFMID: it.FM_ID,
              fromFMTID: it.FMT_ID,
              fromTableID: it.Record_ID,
              fromCatalogID: it.Catalog_ID,
              toFMID: childVisibleConfig.FMT.FM_ID,
              toFMTID: childVisibleConfig.FMT.FMT_ID,
              fromFondsID: it.Fonds_ID,
              toFondsID: catalogStore.treeNode.Fonds_ID,
              toStatus: stateNum[routeData.value.status],
              toParentID: tableSetting.rowClickObj.Record_ID,
              toCatalog_ID: catalogStore.treeNode.Catalog_ID,
              is_Copy: pasteSetting.is_Copy,
              is_CopyJN: true,
              is_CopyAllInfo: pasteFormData.isTrue
            };

      const postWithRetry = async (param: any) => {
        const maxRetry = 2;
        let attempt = 0;
        while (attempt <= maxRetry) {
          try {
            const Res = await proxy.$vueAxios.post("Dynamic/MovePaste", param, { noLoading: true });
            return Res;
          } catch (e) {
            if (attempt === maxRetry) throw e;
          }
          await new Promise(r => setTimeout(r, Math.pow(2, attempt) * 200));
          attempt++;
        }
      };

      const total = items.length;
      const runOne = async (idx: number) => {
        const it = items[idx];
        if (!it) return;

        // 增强暂停检查 - 如果被暂停，等待恢复
        if (!singalrModal.networkStatus || !singalrModal.AllNetworkStatus) {
          // 等待恢复
          while (!singalrModal.networkStatus || !singalrModal.AllNetworkStatus) {
            await new Promise(resolve => setTimeout(resolve, 100)); // 每100ms检查一次

            // 如果用户取消，直接退出
            if (!singalrModal.visible) {
              return;
            }
          }
        }

        singalrModal.circulatingIndex = idx + 1;
        singalrModal.text = `正在复制第${idx + 1}/${total}条数据，档号为${it.Code}`;

        const param = makeParam(it);
        try {
          const Res = await postWithRetry(param);
          if (!Res?.Mark) errList.push(Res?.Msg || `${it.Code} 失败`);
        } catch (e: any) {
          errList.push(e?.message || `${it.Code} 异常`);
        } finally {
          completed++;
          singalrModal.percent = Math.round((completed / total) * 100);
        }
      };

      try {
        // 启动有限并发任务
        let nextIndex = 0;
        const launch = () => {
          while (pending.length < maxConcurrency && nextIndex < total) {
            const p = runOne(nextIndex++).finally(() => {
              const i = pending.indexOf(p as Promise<void>);
              if (i > -1) pending.splice(i, 1);
            });
            pending.push(p as Promise<void>);
          }
        };
        launch();
        while (nextIndex < total || pending.length) {
          // 增强暂停检查
          if (!singalrModal.networkStatus || !singalrModal.AllNetworkStatus) {
            // 如果被暂停，等待恢复
            while (!singalrModal.networkStatus || !singalrModal.AllNetworkStatus) {
              await new Promise(resolve => setTimeout(resolve, 100));

              // 如果用户取消，直接退出
              if (!singalrModal.visible) {
                return;
              }
            }

            // 恢复后继续
            proxy.$message.success("粘贴操作已恢复");
          }

          await Promise.race(pending);
          launch();
        }

        // 刷新数据
        if (pasteSetting.type === "folder") {
          if (dynamicStore.noCatalogStatus) {
            noClassManage();
          } else {
            getPageData();
          }
        } else {
          getChildTableData();
        }

        if (errList.length > 0) {
          proxy.$message.error("部分数据处理失败");
        } else {
          proxy.$message.success("操作成功");
        }
      } catch (error) {
        proxy.$message.error("操作失败");
        getPageData();
      } finally {
        singalrModal.circulatingIndex = 0;
        singalrModal.percent = 0;
        singalrModal.visible = false;
        singalrModal.discontinueStatus = false;
        singalrModal.networkStatus = true;
        singalrModal.discontinueFont = "中止";
        singalrModal.AllNetworkStatus = false;
      }
    };
    // 中止请求 - 修复后的版本
    const cease = () => {
      singalrModal.discontinueStatus = !singalrModal.discontinueStatus;

      if (singalrModal.discontinueStatus) {
        // 暂停操作
        singalrModal.networkStatus = false;
        singalrModal.AllNetworkStatus = false;
        singalrModal.discontinueFont = "恢复";
        singalrModal.text = "粘贴操作已暂停";
        proxy.$message.info("粘贴操作已暂停，点击'恢复'可继续");
      } else {
        // 恢复操作
        singalrModal.networkStatus = true;
        singalrModal.AllNetworkStatus = true;
        singalrModal.discontinueFont = "中止";

        // 恢复进度显示
        const currentIndex = singalrModal.circulatingIndex;
        if (currentIndex > 0) {
          singalrModal.text = `正在复制第${currentIndex}条数据...`;
        }

        proxy.$message.success("粘贴操作已恢复");
      }

      // 移除这行错误的代码
      // new ButtonClick().ParentClickEvent("删除", proxy);
    };
    // 取消请求 - 增强版本
    const cancel = () => {
      // 立即停止所有操作
      singalrModal.AllNetworkStatus = false;
      singalrModal.networkStatus = false;

      // 清理状态
      singalrModal.circulatingIndex = 0;
      singalrModal.percent = 0;
      singalrModal.visible = false;
      singalrModal.discontinueStatus = false;
      singalrModal.discontinueFont = "中止";

      // 清理正在进行的异步操作 - 通过重置状态来停止
      // 注意：pending和completed变量在pasteHandle函数作用域内
      // 这里通过设置状态标志来停止操作

      proxy.$message.info("粘贴操作已取消");
    };

    // 添加暂停状态指示函数
    const getPauseStatusText = () => {
      if (!singalrModal.networkStatus || !singalrModal.AllNetworkStatus) {
        return "已暂停";
      }
      return "处理中";
    };
    // 流水号移至确认事件
    const LSHMoveHandle = () => {
      if (LSHMoveSetting.type === "folder") {
        proxy.$vueAxios
          .post("Dynamic/MoveOrder", {
            tableName: dynamicStore.visibleConfig.FMT.FMT_TableName,
            fM_ID: dynamicStore.tableSelect[0].FM_ID,
            fmT_ID: dynamicStore.tableSelect[0].FMT_ID,
            catalog_ID: dynamicStore.tableSelect[0].Catalog_ID,
            record_ID: dynamicStore.tableSelect[0].Record_ID,
            moveOrder: LSHMoveFormData.value.moveOrder,
            isOrder: true,
            fonds_ID: dynamicStore.tableSelect[0].Fonds_ID
          })
          .then((res: any) => {
            if (res.Mark) {
              LSHMoveSetting.visible = false;
              dynamicStore.updateTableData(res.List[0]);
            }
          });
      } else {
        proxy.$vueAxios
          .post("Dynamic/MoveOrder", {
            tableName: dynamicStore.visibleConfig.FMT.FMT_TableName,
            fM_ID: dynamicStore.childTableSelect[0].FM_ID,
            fmT_ID: dynamicStore.childTableSelect[0].FMT_ID,
            catalog_ID: dynamicStore.childTableSelect[0].Catalog_ID,
            record_ID: dynamicStore.childTableSelect[0].Record_ID,
            moveOrder: LSHMoveFormData.value.moveOrder,
            isOrder: false,
            fonds_ID: dynamicStore.childTableSelect[0].Fonds_ID
          })
          .then((res: any) => {
            if (res.Mark) {
              LSHMoveSetting.visible = false;
              dynamicStore.setChildTableSelect([res.List[0]]);
            }
          });
      }
    };
    // 标记备注勾选框改变事件
    const remarkChange = (val: boolean) => {
      if (val) {
        remarkFormData.color = "";
        remarkFormData.content = "";
      }
    };
    // 标记备注确认事件
    const remarkHandle = () => {
      remarkForm.value.validate((valid: boolean) => {
        if (valid) {
          if (remarkSetting.type === "folder") {
            proxy.$vueAxios
              .post("Dynamic/ChangeMark", {
                fmT_ID: dynamicStore.tableSelect[0].FMT_ID,
                ids: dynamicStore.tableSelect.map((v: any) => v.Record_ID),
                markColor: remarkFormData.color,
                markContent: remarkFormData.content
              })
              .then((res: any) => {
                if (res.Mark) {
                  dynamicStore.tableSelect.forEach(item => {
                    item.MarkColor = remarkFormData.color;
                    item.MarkContent = remarkFormData.content;
                  });
                  proxy.$message.success("操作成功");
                  remarkSetting.visible = false;
                } else {
                  remarkSetting.visible = false;
                  proxy.$message.error("操作失败");
                }
              });
          } else {
            proxy.$vueAxios
              .post("Dynamic/ChangeMark", {
                fmT_ID: dynamicStore.childTableSelect[0].FMT_ID,
                ids: dynamicStore.childTableSelect.map((v: any) => v.Record_ID),
                markColor: remarkFormData.color,
                markContent: remarkFormData.content
              })
              .then((res: any) => {
                if (res.Mark) {
                  dynamicStore.childTableSelect.forEach(item => {
                    item.MarkColor = remarkFormData.color;
                    item.MarkContent = remarkFormData.content;
                  });
                  proxy.$message.success("操作成功");
                  remarkSetting.visible = false;
                } else {
                  remarkSetting.visible = false;
                  proxy.$message.error("操作失败");
                }
              });
          }
        }
      });
    };
    // 数据查重确认事件
    const dataCheckHandle = () => {
      const stateNum: any = {
        Collect: 1,
        Arrangement: 2,
        Storage: 3,
        Utilization: 4
      };
      dataCheckForm.value.validate((valid: boolean) => {
        if (valid) {
          if (dataCheckSetting.type === "folder") {
            proxy.$vueAxios
              .get("Dynamic/DistinctGet", {
                fmid: routeData.value.fmid,
                fmtid: routeData.value.fmtid,
                status: stateNum[routeData.value.status],
                groupby: dataCheckFormData.field.join(",")
              })
              .then((res: any) => {
                if (res.Mark) {
                  proxy.$message.success("操作成功");
                  dynamicStore.setTableData(res.List);
                } else {
                  proxy.$message.error("操作失败");
                }
                dataCheckSetting.visible = false;
              });
          } else {
            proxy.$vueAxios
              .get("Dynamic/DistinctGet", {
                fmid: dynamicStore.childTableData[0].FM_ID,
                fmtid: dynamicStore.childTableData[0].FMT_ID,
                groupby: dataCheckFormData.field.join(",")
              })
              .then((res: any) => {
                if (res.Mark) {
                  proxy.$message.success("操作成功");
                  dynamicStore.setChildTableData(res.List);
                } else {
                  proxy.$message.error("操作失败");
                }
                dataCheckSetting.visible = false;
              });
          }
        }
      });
    };
    // 重置流水号
    const resetLSHHandle = async () => {
      const { tableSelect, visibleConfig } = dynamicStore;
      for (let i = 0; i < tableSelect.length; i++) {
        delete tableSelect[i].checkbox;
        const modalFormData = { ...tableSelect[i], Order: resetLSHFormData.lsh_start + i };
        const FieldRuleClass = new RuleClass({
          modalFormData: modalFormData,
          ruleList: visibleConfig.FieldRule.filter((v: any) => v.FR_Enable === true),
          tableName: visibleConfig.FMT.FMT_TableName
        }); // 执行字段规则类方法
        FieldRuleClass.fieldRuleEvent2();
        await proxy.$vueAxios
          .put(
            "Dynamic",
            {
              list: [{ ...modalFormData }],
              tableName: visibleConfig.FMT.FMT_TableName
            },
            { noLoading: true }
          )
          .then((res: any) => {
            if (res.Mark) {
              dynamicStore.updateTableData(res.List[0]);
            }
          });
      }
      resetLSH.visible = false;
    };

    // 四性检测抽屉展示操作
    const showFourAspectRecords = (row: any) => {
      console.log("拿到当前行数据----", row);
      fourAspectRecordsClickRow.value = row;
      isShowFourAspectRecords.value = true;
    };

    // 显示主表元数据弹框
    const showFolderMetaData = (row: any) => {
      metaDataSetting.visible = true;
      nextTick(() => {
        metaDataRef.value.activeName = "1";
        metaDataRef.value.record = row;
        metaDataRef.value.getTableData1(row);
      });
    };
    const showFileMetaData = (row: any) => {
      metaDataSetting.visible = true;
      nextTick(() => {
        metaDataRef.value.activeName = "1";
        metaDataRef.value.record = row;
        metaDataRef.value.getTableData1(row);
      });
    };
    // 拆卷确认
    const dismantleHandle = async () => {
      const { tableSelect, visibleConfig, childTableSelect, childVisibleConfig } = dynamicStore;
      if (dismantleSetting.type === "folder") {
        for (let i = 0; i < tableSelect.length; i++) {
          delete tableSelect[i].checkbox;
          const modalFormData = {
            ...tableSelect[i],
            Parent_ID: null,
            Catalog_ID: dismantleSetting.isTrue ? null : tableSelect[i].Catalog_ID,
            Code: null
          };
          await proxy.$vueAxios
            .put(
              "Dynamic",
              {
                list: [{ ...modalFormData }],
                tableName: visibleConfig.FMT.FMT_TableName
              },
              { noLoading: true }
            )
            .then((res: any) => {
              if (res.Mark) {
                dynamicStore.updateTableData(res.List[0]);
              }
            });
          if (dismantleSetting.isTrue) {
            const index2 = dynamicStore.tableData.findIndex((v: any) => v.Record_ID === tableSelect[i].Record_ID);
            if (index2 > -1) {
              dynamicStore.tableData.splice(index2, 1);
            }
          }
        }
      } else {
        for (let i = 0; i < childTableSelect.length; i++) {
          delete childTableSelect[i].checkbox;
          const modalFormData = {
            ...childTableSelect[i],
            Parent_ID: null,
            Catalog_ID: dismantleSetting.isTrue ? null : childTableSelect[i].Catalog_ID,
            Code: null
          };
          await proxy.$vueAxios
            .put(
              "Dynamic",
              {
                list: [{ ...modalFormData }],
                tableName: childVisibleConfig.FMT.FMT_TableName
              },
              { noLoading: true }
            )
            .then((res: any) => {
              if (res.Mark) {
                dynamicStore.updateChildTableData(res.List[0]);
              }
            });
          const index3 = dynamicStore.childTableData.findIndex((v: any) => v.Record_ID === childTableSelect[i].Record_ID);

          if (index3 > -1) {
            dynamicStore.childTableData.splice(index3, 1);
          }
        }
      }
      dismantleSetting.visible = false;
    };
    // 查询归卷下拉框切换事件
    const queryTheVolumeSelectChange = (val: string) => {
      proxy.$vueAxios
        .get(
          "MasterBaseFormModelTable/GetInitialize",
          {
            fmtId: val
          },
          { noLoading: true }
        )
        .then((res: any) => {
          console.log(res.List[0]);
          queryTheVolumeRule.value = res.List[0];
        });
    };
    // 查询归卷表格选中事件
    const queryTheVolumeTableSelect = (val: any[]) => {
      queryTheVolumeTableSetting.selectData = val;
    };
    // 查询归卷左侧树点击事件
    const onQueryTheVolumeTreeClick = (treeNode: any) => {
      const stateName: any = {
        1: "Collect",
        2: "Arrangement",
        3: "Storage",
        4: "Utilization"
      };
      const params = {
        fmid: tableSetting.rowClickObj.FM_ID,
        fmtid: queryTheVolumeSelect.value,
        catalogid: treeNode.Catalog_ID,
        status: routeData.value.status,
        searchType: 5,
        pageIndex: 1,
        pageSize: 3000000,
        parentid: null
      };
      proxy.$vueAxios.get("Dynamic/CommonGet", params, { noLoading: true }).then((res: any) => {
        queryTheVolumeTableSetting.data = res.List;
        queryTheVolumeTableSetting.sourceData = res.List;
      });
    };
    //查询归卷点击无分类
    const noQueryTheVolumeTreeClassMana = () => {
      const stateName: any = {
        1: "Collect",
        2: "Arrangement",
        3: "Storage",
        4: "Utilization"
      };
      const params = {
        fmid: tableSetting.rowClickObj.FM_ID,
        fmtid: queryTheVolumeSelect.value,
        status: routeData.value.status,
        searchType: 5, // leftTreeObj.value ? 1 : 2,
        pageIndex: 1,
        pageSize: 3000000,
        parentid: null
      };
      proxy.$vueAxios.get("Dynamic/CommonGet", params, { noLoading: true }).then((res: any) => {
        queryTheVolumeTableSetting.data = res.List;
        queryTheVolumeTableSetting.sourceData = res.List;
      });
    };
    // 查询归卷确认
    const queryTheVolumeHandle = async () => {
      const fmtItem = (FMTData.value as any[]).find((v: any) => v.FMT_ID === queryTheVolumeSelect.value);
      const tableName = fmtItem?.FMT_TableName;
      if (!tableName) return;

      for (let i = 0; i < queryTheVolumeTableSetting.selectData.length; i++) {
        const item = {
          ...queryTheVolumeTableSetting.selectData[i],
          Catalog_ID: tableSetting.rowClickObj.Catalog_ID,
          Parent_ID: tableSetting.rowClickObj.Record_ID,
          Status: tableSetting.rowClickObj.Status
        };
        delete (item as any).checkbox;
        delete (item as any)._X_ROW_KEY;
        const FieldRuleClass = new RuleClass({
          modalFormData: item,
          ruleList: (queryTheVolumeRule.value as any)?.FieldRule?.filter((v: any) => v.FR_Enable === true) || [],
          tableName: tableName
        }); // 执行字段规则类方法
        await FieldRuleClass.fieldRuleEvent2();
        console.log(item);

        await proxy.$vueAxios
          .put(
            "Dynamic",
            {
              list: [{ ...item }],
              tableName: tableName
            },
            { noLoading: true }
          )
          .then((res: any) => {
            if (res.Mark) {
              const index = queryTheVolumeTableSetting.data.findIndex((v: any) => v.Record_ID === item.Record_ID);
              if (index > -1) {
                queryTheVolumeTableSetting.data.splice(index, 1);
              }
            }
          });
        // 获取子表数据
        const childTableRes = await proxy.$vueAxios.get(
          "Dynamic/CommonChildTableGet",
          {
            fmid: tableSetting.rowClickObj.FM_ID,
            dataId: tableSetting.rowClickObj.Record_ID,
            fmtType: childData.value[activeName.value].FMT_Type
          },
          { noLoading: true }
        );
        if (childTableRes.Mark) {
          childTableSetting.childTableData = childTableRes.List;
          childTableSetting.childLoading = false;
          dynamicStore.setChildTableData(childTableRes.List);
          dynamicStore.setChildSourthTableData(childTableRes.List);
        }
      }
    };
    // 查询归卷搜索功能
    const queryTheVolumeInputChange = () => {
      console.log(queryTheVolumeInput.value);
      queryTheVolumeTableSetting.data = queryTheVolumeTableSetting.sourceData.filter((v: any) => {
        // console.log(ACrypto.getSS(v.Title));
        // if()
        return (
          ACrypto.getSS(v.Title)?.includes(queryTheVolumeInput.value.trim()) ||
          v.Year?.toString().includes(queryTheVolumeInput.value.trim()) ||
          v.FileNumber?.includes(queryTheVolumeInput.value.trim()) ||
          v.WorkFlow_ID_InterFace?.includes(queryTheVolumeInput.value.trim()) ||
          v.Create_DateTime?.toString().includes(queryTheVolumeInput.value.trim()) ||
          v.ReceiptCode?.includes(queryTheVolumeInput.value.trim())
        );
      });
    };
    // 重置流水号
    const resetLSHEvent = async () => {
      let order = LSHSetting.startLSH;
      LSHSetting.loading = true;
      LSHSetting.btnLoading = true;
      for (let i = 0; i < LSHSetting.data.length; i++) {
        LSHSetting.loadingText = `正在加载第${i + 1}条数据...`;
        const item = cloneDeep(LSHSetting.data[i]) as any;
        delete item.checkbox;
        delete item.ROWINDEX;
        let modalFormData = {};
        if (LSHSetting.orderType === "Order") {
          modalFormData = { ...item, Order: order++ };
        } else {
          modalFormData = { ...item, SmallOrder: order++ };
          // LSHSetting.orderType
        }
        const FieldRuleClass = new RuleClass({
          modalFormData: modalFormData,
          ruleList: LSHSetting.ruleList,
          tableName: LSHSetting.tableName
        }); // 执行字段规则类方法
        FieldRuleClass.fieldRuleEvent2();
        const res = await proxy.$vueAxios.put(
          "Dynamic",
          {
            list: [{ ...modalFormData, _X_ROW_KEY: undefined }],
            tableName: LSHSetting.tableName
          },
          { noLoading: true }
        );
        if (res.Mark) {
          (LSHSetting.data[i] as any)[LSHSetting.orderType] = res.List[0][LSHSetting.orderType];
          (LSHSetting.data[i] as any).Code = res.List[0].Code;
          // dynamicStore.updateTableData(res.List[0]);
        }
      }
      LSHSetting.loading = false;
      LSHSetting.btnLoading = false;
    };
    // 流水号表格点击事件
    const LSHRowClick = ({ row, rowIndex }: any) => {
      LSHSetting.rowClickObj = row;
      LSHSetting.LShTableIndex = rowIndex;
      console.log(LSHSetting.LShTableIndex);
    };
    // 流水号上移
    const sortUpLSH = async (index: number) => {
      if (index <= 0) {
        proxy.$message.warning("已经是第一条了");
        return;
      }
      LSHSetting.loading = true;
      LSHSetting.loadingText = `正在上移...`;
      LSHSetting.btnLoading2 = true;
      const newData = cloneDeep(LSHSetting.data) as any[];
      let temp = newData[index - 1];
      let tempOrder = (newData[index - 1] as any)[LSHSetting.orderType];
      (newData[index - 1] as any)[LSHSetting.orderType] = (newData[index] as any)[LSHSetting.orderType];
      (newData[index] as any)[LSHSetting.orderType] = tempOrder;
      newData.splice(index - 1, 1);
      newData.splice(index, 0, temp);
      const FieldRuleClass = new RuleClass({
        modalFormData: newData[index],
        ruleList: LSHSetting.ruleList,
        tableName: LSHSetting.tableName
      });
      // 执行字段规则类方法
      FieldRuleClass.fieldRuleEvent2();
      const FieldRuleClass2 = new RuleClass({
        modalFormData: newData[index - 1],
        ruleList: LSHSetting.ruleList,
        tableName: LSHSetting.tableName
      });
      // 执行字段规则类方法
      FieldRuleClass2.fieldRuleEvent2();
      await proxy.$vueAxios.put(
        "Dynamic",
        {
          list: [{ ...newData[index], _X_ROW_KEY: undefined }],
          tableName: LSHSetting.tableName
        },
        { noLoading: true }
      );
      await proxy.$vueAxios.put(
        "Dynamic",
        {
          list: [{ ...newData[index - 1], _X_ROW_KEY: undefined }],
          tableName: LSHSetting.tableName
        },
        { noLoading: true }
      );
      LSHSetting.data = newData;
      if (LSHSetting.LShTableIndex > 0) {
        LSHSetting.LShTableIndex -= 1;
      }
      LSHSetting.loading = false;
      LSHSetting.btnLoading2 = false;
    };
    // 流水号下移
    const sortDownLSH = async (index: number) => {
      console.log(LSHSetting.ruleList, LSHSetting.tableName);

      if (index >= LSHSetting.data.length - 1) {
        proxy.$message.warning("已经是最后一条了");
        return;
      }
      LSHSetting.loading = true;
      LSHSetting.loadingText = `正在下移...`;
      LSHSetting.btnLoading3 = true;
      const newData = cloneDeep(LSHSetting.data) as any[];
      const temp = newData[index + 1];
      const tempOrder = (newData[index + 1] as any)[LSHSetting.orderType];
      (newData[index + 1] as any)[LSHSetting.orderType] = (newData[index] as any)[LSHSetting.orderType];
      (newData[index] as any)[LSHSetting.orderType] = tempOrder;
      newData.splice(index + 1, 1);
      newData.splice(index, 0, temp);

      const FieldRuleClass = new RuleClass({
        modalFormData: newData[index],
        ruleList: LSHSetting.ruleList,
        tableName: LSHSetting.tableName
      });
      // 执行字段规则类方法
      FieldRuleClass.fieldRuleEvent2();
      const FieldRuleClass2 = new RuleClass({
        modalFormData: newData[index + 1],
        ruleList: LSHSetting.ruleList,
        tableName: LSHSetting.tableName
      });
      // 执行字段规则类方法
      FieldRuleClass2.fieldRuleEvent2();
      const res = await proxy.$vueAxios.put(
        "Dynamic",
        {
          list: [{ ...newData[index], _X_ROW_KEY: undefined }],
          tableName: LSHSetting.tableName
        },
        { noLoading: true }
      );
      const res2 = await proxy.$vueAxios.put(
        "Dynamic",
        {
          list: [{ ...newData[index + 1], _X_ROW_KEY: undefined }],
          tableName: LSHSetting.tableName
        },
        { noLoading: true }
      );
      LSHSetting.data = newData;
      if (LSHSetting.LShTableIndex < LSHSetting.data.length - 1) {
        LSHSetting.LShTableIndex += 1;
      }
      LSHSetting.loading = false;
      LSHSetting.btnLoading3 = false;
    };
    // 流水号移至
    const LSHTo = async () => {
      if (!LSHSetting.endLSH || LSHSetting.endLSH <= 0) {
        proxy.$message.warning("流水号不能小于1");
        return;
      } else if (LSHSetting.endLSH == LSHSetting.LShTableIndex + 1) {
        proxy.$message.warning("流水号不能移至相同位置");
        return;
      } else if (LSHSetting.endLSH > LSHSetting.data.length) {
        proxy.$message.warning("流水号不能超出总行数");
        return;
      }
      LSHSetting.loading = true;
      LSHSetting.loadingText = `正在移至流水...`;
      LSHSetting.btnLoading4 = true;
      // 深拷贝数据源
      const newData = cloneDeep(LSHSetting.data) as any[];
      // 要移至的目标对象order
      const tempOrder = (newData[LSHSetting.endLSH - 1] as any)[LSHSetting.orderType];
      // 将当前选中的数据order改为要移至的目标对象order
      (newData[LSHSetting.LShTableIndex] as any)[LSHSetting.orderType] = tempOrder;
      // 获取当前选中的数据
      const element = newData[LSHSetting.LShTableIndex];
      // 获取删除选中数据之后的数组
      newData.splice(LSHSetting.LShTableIndex, 1);
      // 将选中元素插入到要移至元素原来的位置
      newData.splice(LSHSetting.endLSH - 1, 0, element);

      // 执行字段规则
      const FieldRuleClass = new RuleClass({
        modalFormData: element,
        ruleList: LSHSetting.ruleList,
        tableName: LSHSetting.tableName
      });
      // 执行字段规则类方法
      FieldRuleClass.fieldRuleEvent2();
      // 修改数据到数据库
      await proxy.$vueAxios.put(
        "Dynamic",
        {
          list: [{ ...element, _X_ROW_KEY: undefined }],
          tableName: LSHSetting.tableName
        },
        { noLoading: true }
      );
      if (LSHSetting.LShTableIndex > LSHSetting.endLSH - 1) {
        for (let i = LSHSetting.LShTableIndex; LSHSetting.endLSH - 1 < i; i--) {
          const item = newData[i];
          item[LSHSetting.orderType] = parseInt(item[LSHSetting.orderType]) + 1;
          // 执行字段规则
          const FieldRuleClass = new RuleClass({
            modalFormData: item,
            ruleList: LSHSetting.ruleList,
            tableName: LSHSetting.tableName
          });
          // 执行字段规则类方法
          FieldRuleClass.fieldRuleEvent2();
          // 修改数据到数据库
          const res = await proxy.$vueAxios.put(
            "Dynamic",
            {
              list: [{ ...item, _X_ROW_KEY: undefined }],
              tableName: LSHSetting.tableName
            },
            { noLoading: true }
          );
        }
      } else {
        for (let i = LSHSetting.LShTableIndex; i < LSHSetting.endLSH - 1; i++) {
          const item = newData[i];
          item[LSHSetting.orderType] = parseInt(item[LSHSetting.orderType]) - 1;
          // 执行字段规则
          const FieldRuleClass = new RuleClass({
            modalFormData: item,
            ruleList: LSHSetting.ruleList,
            tableName: LSHSetting.tableName
          });
          // 执行字段规则类方法
          FieldRuleClass.fieldRuleEvent2();
          // 修改数据到数据库
          const res = await proxy.$vueAxios.put(
            "Dynamic",
            {
              list: [{ ...item, _X_ROW_KEY: undefined }],
              tableName: LSHSetting.tableName
            },
            { noLoading: true }
          );
        }
      }
      LSHSetting.data = newData;
      LSHSetting.loading = false;
      LSHSetting.btnLoading4 = false;
      LSHSetting.LShTableIndex = LSHSetting.endLSH - 1;
    };
    // 流水操作确认事件
    const LSHandle = () => {
      LSHSetting.visible = false;

      if (LSHSetting.type === 1) {
        getPageData();
      } else if (LSHSetting.type === 2) {
        getChildTableData();
      }
    };
    // 搜索弹框确认事件
    const searchHandle = () => {
      searchSetting.visible = false;
    };
    // 点击回收站按钮
    const recycle = () => {
      headerHeight.value = 42;
      const el = document.querySelector(".vxe-grid--toolbar-wrapper") as any;
      if (globalStore.assemblySize === "default") {
        el.style.height = "47px";
      } else if (globalStore.assemblySize === "large") {
        el.style.height = "57px";
      } else if (globalStore.assemblySize === "small") {
        el.style.height = "37px";
      }
      recycleStatus.value = true;
      topBarShow.value = false;
      tableSetting.loading = true;
      recycleBtnStatus.value = [true, true];
      dynamicStore.childTableData = [];
      dynamicStore
        .getTableData({
          fmid: routeData.value.fmid,
          fmtid: routeData.value.fmtid,
          status: routeData.value.status,
          Create_By: userStore.userInfo.U_ID,
          searchType: 10,
          pageIndex: 1,
          pageSize: dynamicStore.pageSize ? dynamicStore.pageSize : 0,
          parentid: routeData.value.fatherObj
            ? JSON.parse(decodeURIComponent(routeData.value.fatherObj as any)).Record_ID
            : undefined,
          isDelete: true
        })
        .then((res: any) => {
          tableSetting.loading = false;
          dynamicStore.setTableData(res.List);
          dynamicStore.setSourthTableData(res.List);
        })
        .catch(() => {
          tableSetting.loading = false;
        });
    };
    // 还原
    const restore = async () => {
      for (let i = 0; i < dynamicStore.tableSelect.length; i++) {
        console.log(i);
        const item = dynamicStore.tableSelect[i];
        console.log("1111111111111111111111111111111", item);

        const Res = await proxy.$vueAxios.put(
          "Dynamic",
          {
            list: [{ Record_ID: item.Record_ID, FMT_ID: item.FMT_ID, FM_ID: item.FM_ID, IsDelete: false }],
            tableName: dynamicStore.visibleConfig.FMT.FMT_TableName
          },
          { noLoading: true }
        );
        if (Res.Mark) {
          // dynamicStore.delTableSelectData(
          //   dynamicStore.tableSelect.splice(
          //     dynamicStore.tableSelect.findIndex((v: any) => v.Record_ID === item.Record_ID),
          //     1
          //   )
          // );
          dynamicStore.tableData.splice(
            dynamicStore.tableData.findIndex((v: any) => v.Record_ID === item.Record_ID),
            1
          );
        }
      }
      dynamicStore.tableSelect = [];
      dynamicStore.childTableData = [];
      recycleBtnStatus.value = [true, true];
    };
    // 删除回收站
    const recycleDel = async () => {
      proxy
        .$confirm("删除后将无法找回", "确认要删除数据吗？", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
        .then(async () => {
          for (let i = 0; i < dynamicStore.tableSelect.length; i++) {
            const item = dynamicStore.tableSelect[i];
            const Res = await proxy.$vueAxios.delete2(
              "Dynamic",
              {
                list: [{ Record_ID: item.Record_ID, FMT_ID: item.FMT_ID, FM_ID: item.FM_ID }],
                tableName: dynamicStore.visibleConfig.FMT.FMT_TableName
              },
              { noLoading: true }
            );
            if (Res.Mark) {
              // dynamicStore.delTableSelectData(
              //   dynamicStore.tableSelect.splice(
              //     dynamicStore.tableSelect.findIndex((v: any) => v.Record_ID === item.Record_ID),
              //     1
              //   )
              // );
              dynamicStore.tableData.splice(
                dynamicStore.tableData.findIndex((v: any) => v.Record_ID === item.Record_ID),
                1
              );
            }
          }
          dynamicStore.tableSelect = [];
          dynamicStore.childTableData = [];
          recycleBtnStatus.value = [true, true];
        });
    };
    // url借阅点击确认
    const urlBorrow = () => {
      urlModal.isShow = false;
      proxy.$message.success("借阅成功");
    };
    const LabelHandle = async () => {
      // 获取选中的标签DDL_ID数组
      const selectedLabelIds: string[] = [];
      selectedItems.value.forEach((isSelected, index) => {
        if (isSelected && dictionary["labels"] && dictionary["labels"][index]) {
          selectedLabelIds.push(dictionary["labels"][index].DDL_ID);
        }
      });

      // 分析每个标签的状态（全色、半色、无色）
      const labelStatusMap: Record<string, { isFull: boolean; isPartial: boolean; recordIds: string[] }> = {};

      // 初始化标签状态
      selectedLabelIds.forEach(labelId => {
        labelStatusMap[labelId] = {
          isFull: false,
          isPartial: false,
          recordIds: []
        };
      });

      // 检查每个标签在现有数据中的使用情况
      if (labelStatusData.value.length > 0) {
        selectedLabelIds.forEach(labelId => {
          const recordsWithLabel = labelStatusData.value.filter((record: any) => record.lable_id === labelId);
          const recordIds = recordsWithLabel.map((record: any) => record.record_id);
          const totalSelected = dynamicStore.tableSelect.length;
          const hasLabelCount = recordIds.length;

          labelStatusMap[labelId] = {
            isFull: hasLabelCount === totalSelected && totalSelected > 0,
            isPartial: hasLabelCount > 0 && hasLabelCount < totalSelected,
            recordIds: recordIds
          };
        });
      }

      // 删除标签记录
      await proxy.$vueAxios.post("Master_Base_LableRecord/DeleteByColumnName", {
        columnName: "Record_ID",
        ids: dynamicStore.tableSelect.map((item: any) => item.Record_ID)
      });

      // 为每个选中的数据行添加标签记录
      const labelRecordList: any[] = [];

      for (let i = 0; i < dynamicStore.tableSelect.length; i++) {
        const item = dynamicStore.tableSelect[i];
        // 为每个选中的标签创建记录
        for (let j = 0; j < selectedLabelIds.length; j++) {
          const labelId = selectedLabelIds[j];
          const labelStatus = labelStatusMap[labelId];

          // 如果是半色标签，只对原来没有此标签的数据添加标签
          if (labelStatus.isPartial && !labelStatus.recordIds.includes(item.Record_ID)) {
            labelRecordList.push({
              fmt_id: routeData.value.fmtid,
              record_id: item.Record_ID,
              lable_id: labelId,
              lable_Create_By: userStore.userInfo.U_ID,
              lable_Create_Time: dtime(new Date().getTime()).format("YYYY-MM-DD HH:mm:ss")
            });
          } else if (labelStatus.isFull || !labelStatus.isPartial) {
            // 如果是全色标签或新标签，为所有数据添加标签
            labelRecordList.push({
              fmt_id: routeData.value.fmtid,
              record_id: item.Record_ID,
              lable_id: labelId,
              lable_Create_By: userStore.userInfo.U_ID,
              lable_Create_Time: dtime(new Date().getTime()).format("YYYY-MM-DD HH:mm:ss")
            });
          }
        }
      }

      // 批量添加标签记录
      if (labelRecordList.length > 0) {
        await proxy.$vueAxios.post("Master_Base_LableRecord/AddList", labelRecordList, { noLoading: true });
      }

      // 同步更新目录数据的lables字段
      if (selectedLabelIds.length > 0) {
        // 获取全色标签ID（所有选中的数据都拥有的标签）
        const fullColorLabelIds: string[] = [];

        for (const labelId of selectedLabelIds) {
          const labelStatus = labelStatusMap[labelId];
          if (labelStatus.isFull || (!labelStatus.isPartial && labelStatus.recordIds.length === 0)) {
            fullColorLabelIds.push(labelId);
          }
        }

        // 更新每个选中数据的lables字段
        for (const item of dynamicStore.tableSelect) {
          if (dynamicStore.tableSelect.length > 1) {
            if (fullColorLabelIds.length > 0) {
              // 将原来的标签和新的全色标签合并，然后去重
              const originalLabels =
                item.lables && item.lables.trim() ? item.lables.split(",").filter((id: string) => id.trim()) : [];
              const allLabels = [...originalLabels, ...fullColorLabelIds];
              const uniqueLabels = [...new Set(allLabels)];
              // 将全色标签ID用逗号连接，存储到lables字段
              item.lables = uniqueLabels.join(",");
            } else {
              // 如果没有全色标签，将lables字段设为空字符串
              item.lables = "";
            }
          } else if (fullColorLabelIds.length > 0) {
            // 将全色标签ID用逗号连接，存储到lables字段
            item.lables = fullColorLabelIds.join(",");
          } else {
            // 如果没有全色标签，将lables字段设为空字符串
            item.lables = "";
          }

          // 更新数据库中的lables字段
          await proxy.$vueAxios.put(
            "Dynamic",
            {
              list: [
                {
                  Record_ID: item.Record_ID,
                  FMT_ID: item.FMT_ID,
                  FM_ID: item.FM_ID,
                  lables: item.lables
                }
              ],
              tableName: dynamicStore.visibleConfig.FMT.FMT_TableName
            },
            { noLoading: true }
          );
        }
      } else {
        // 当没有选中任何标签时，将所有勾选目录数据的lables字段设为空字符串
        for (const item of dynamicStore.tableSelect) {
          item.lables = "";

          // 更新数据库中的lables字段
          await proxy.$vueAxios.put(
            "Dynamic",
            {
              list: [
                {
                  Record_ID: item.Record_ID,
                  FMT_ID: item.FMT_ID,
                  FM_ID: item.FM_ID,
                  lables: ""
                }
              ],
              tableName: dynamicStore.visibleConfig.FMT.FMT_TableName
            },
            { noLoading: true }
          );
        }
      }

      // 关闭弹框并重置选中状态
      LabelSetting.visible = false;
      selectedItems.value = new Array(dictionary["labels"]?.length).fill(false);
      proxy.$message.success("标签设置成功");
    };
    // 子级设置弹框窗体确认按钮
    const LabelHandle2 = async () => {
      // 获取选中的标签DDL_ID数组
      const selectedLabelIds: string[] = [];
      selectedItems2.value.forEach((isSelected, index) => {
        if (isSelected && dictionary["labels"] && dictionary["labels"][index]) {
          selectedLabelIds.push(dictionary["labels"][index].DDL_ID);
        }
      });

      // 分析每个标签的状态（全色、半色、无色）
      const labelStatusMap: Record<string, { isFull: boolean; isPartial: boolean; recordIds: string[] }> = {};

      // 初始化标签状态
      selectedLabelIds.forEach(labelId => {
        labelStatusMap[labelId] = {
          isFull: false,
          isPartial: false,
          recordIds: []
        };
      });

      // 检查每个标签在现有数据中的使用情况
      if (labelStatusData2.value.length > 0) {
        selectedLabelIds.forEach(labelId => {
          const recordsWithLabel = labelStatusData2.value.filter((record: any) => record.lable_id === labelId);
          const recordIds = recordsWithLabel.map((record: any) => record.record_id);
          const totalSelected = dynamicStore.childTableSelect.length;
          const hasLabelCount = recordIds.length;

          labelStatusMap[labelId] = {
            isFull: hasLabelCount === totalSelected && totalSelected > 0,
            isPartial: hasLabelCount > 0 && hasLabelCount < totalSelected,
            recordIds: recordIds
          };
        });
      }

      // 删除标签记录
      await proxy.$vueAxios.post("Master_Base_LableRecord/DeleteByColumnName", {
        columnName: "Record_ID",
        ids: dynamicStore.childTableSelect.map((item: any) => item.Record_ID)
      });

      // 为每个选中的数据行添加标签记录
      const labelRecordList: any[] = [];

      for (let i = 0; i < dynamicStore.childTableSelect.length; i++) {
        const item = dynamicStore.childTableSelect[i];
        // 为每个选中的标签创建记录
        for (let j = 0; j < selectedLabelIds.length; j++) {
          const labelId = selectedLabelIds[j];
          const labelStatus = labelStatusMap[labelId];

          // 如果是半色标签，只对原来没有此标签的数据添加标签
          if (labelStatus.isPartial && !labelStatus.recordIds.includes(item.Record_ID)) {
            labelRecordList.push({
              fmt_id: routeData.value.fmtid,
              record_id: item.Record_ID,
              lable_id: labelId,
              lable_Create_By: userStore.userInfo.U_ID,
              lable_Create_Time: dtime(new Date().getTime()).format("YYYY-MM-DD HH:mm:ss")
            });
          } else if (labelStatus.isFull || !labelStatus.isPartial) {
            // 如果是全色标签或新标签，为所有数据添加标签
            labelRecordList.push({
              fmt_id: routeData.value.fmtid,
              record_id: item.Record_ID,
              lable_id: labelId,
              lable_Create_By: userStore.userInfo.U_ID,
              lable_Create_Time: dtime(new Date().getTime()).format("YYYY-MM-DD HH:mm:ss")
            });
          }
        }
      }

      // 批量添加标签记录
      if (labelRecordList.length > 0) {
        await proxy.$vueAxios.post("Master_Base_LableRecord/AddList", labelRecordList, { noLoading: true });
      }

      // 同步更新子级数据的lables字段
      if (selectedLabelIds.length > 0) {
        // 获取全色标签ID（所有选中的数据都拥有的标签）
        const fullColorLabelIds: string[] = [];

        for (const labelId of selectedLabelIds) {
          const labelStatus = labelStatusMap[labelId];
          if (labelStatus.isFull || (!labelStatus.isPartial && labelStatus.recordIds.length === 0)) {
            fullColorLabelIds.push(labelId);
          }
        }

        // 更新每个选中数据的lables字段
        for (const item of dynamicStore.childTableSelect) {
          if (dynamicStore.childTableSelect.length > 1) {
            if (fullColorLabelIds.length > 0) {
              // 将原来的标签和新的全色标签合并，然后去重
              const originalLabels =
                item.lables && item.lables.trim() ? item.lables.split(",").filter((id: string) => id.trim()) : [];
              const allLabels = [...originalLabels, ...fullColorLabelIds];
              const uniqueLabels = [...new Set(allLabels)];
              // 将全色标签ID用逗号连接，存储到lables字段
              item.lables = uniqueLabels.join(",");
            } else {
              // 如果没有全色标签，将lables字段设为空字符串
              item.lables = "";
            }
          } else if (fullColorLabelIds.length > 0) {
            // 将全色标签ID用逗号连接，存储到lables字段
            item.lables = fullColorLabelIds.join(",");
          } else {
            // 如果没有全色标签，将lables字段设为空字符串
            item.lables = "";
          }

          // 更新数据库中的lables字段
          await proxy.$vueAxios.put(
            "Dynamic",
            {
              list: [
                {
                  Record_ID: item.Record_ID,
                  FMT_ID: item.FMT_ID,
                  FM_ID: item.FM_ID,
                  lables: item.lables
                }
              ],
              tableName: dynamicStore.childVisibleConfig.FMT.FMT_TableName
            },
            { noLoading: true }
          );
        }
      } else {
        // 当没有选中任何标签时，将所有勾选子级数据的lables字段设为空字符串
        for (const item of dynamicStore.childTableSelect) {
          item.lables = "";

          // 更新数据库中的lables字段
          await proxy.$vueAxios.put(
            "Dynamic",
            {
              list: [
                {
                  Record_ID: item.Record_ID,
                  FMT_ID: item.FMT_ID,
                  FM_ID: item.FM_ID,
                  lables: ""
                }
              ],
              tableName: dynamicStore.childVisibleConfig.FMT.FMT_TableName
            },
            { noLoading: true }
          );
        }
      }

      // 关闭弹框并重置选中状态
      LabelSetting2.visible = false;
      selectedItems2.value = new Array(dictionary["labels"]?.length).fill(false);
      proxy.$message.success("标签设置成功");
    };
    // 获取选中数据的标签信息
    const getLabelStatusData = async () => {
      if (dynamicStore.tableSelect.length === 0) {
        proxy.$message.warning("请先选择数据");
        return;
      }
      try {
        const recordIds = dynamicStore.tableSelect.map((item: any) => item.Record_ID);
        let allLabelData: any[] = [];
        // 循环每个recordId获取标签数据
        for (let i = 0; i < recordIds.length; i++) {
          const recordId = recordIds[i];
          const res = await proxy.$vueAxios.post(
            "Master_Base_LableRecord/GetConditional",
            {
              order: "lable_Create_Time desc",
              dtoList: [
                {
                  fieldName: "Record_Id",
                  fieldValue: recordId,
                  conditionalType: 0 // 等于查询
                }
              ]
            },
            { noLoading: true }
          );

          if (res.Mark && res.List) {
            allLabelData = allLabelData.concat(res.List);
          }
        }

        labelStatusData.value = allLabelData;
      } catch (error) {
        console.error("获取标签状态失败:", error);
        labelStatusData.value = [];
      }
    };
    // 子级获取选中数据的标签信息
    const getLabelStatusData2 = async () => {
      if (dynamicStore.childTableSelect.length === 0) {
        proxy.$message.warning("请先选择数据");
        return;
      }
      try {
        const recordIds = dynamicStore.childTableSelect.map((item: any) => item.Record_ID);
        let allLabelData: any[] = [];
        // 循环每个recordId获取标签数据
        for (let i = 0; i < recordIds.length; i++) {
          const recordId = recordIds[i];
          const res = await proxy.$vueAxios.post(
            "Master_Base_LableRecord/GetConditional",
            {
              order: "lable_Create_Time desc",
              dtoList: [
                {
                  fieldName: "Record_Id",
                  fieldValue: recordId,
                  conditionalType: 0 // 等于查询
                }
              ]
            },
            { noLoading: true }
          );

          if (res.Mark && res.List) {
            allLabelData = allLabelData.concat(res.List);
          }
        }

        labelStatusData2.value = allLabelData;

        // 根据标签数据设置selectedItems2的状态
        if (dictionary["labels"]) {
          // 重置所有标签的选中状态
          selectedItems2.value = new Array(dictionary["labels"].length).fill(false);

          // 统计每个标签被多少条数据使用
          const labelUsageCount: Record<string, number> = {};
          allLabelData.forEach((record: any) => {
            const labelId = record.lable_id;
            labelUsageCount[labelId] = (labelUsageCount[labelId] || 0) + 1;
          });

          // 设置标签的选中状态
          dictionary["labels"].forEach((label: any, index: number) => {
            const labelId = label.DDL_ID;
            const usageCount = labelUsageCount[labelId] || 0;

            if (usageCount > 0) {
              // 只要有数据使用此标签，就设置为选中状态
              selectedItems2.value[index] = true;
            }
          });
        }
      } catch (error) {
        console.error("获取标签状态失败:", error);
        labelStatusData2.value = [];
      }
    };
    // 计算父级标签的背景样式类
    const getLabelClass = (labelId: string) => {
      // 找到标签在字典中的索引
      const labelIndex = dictionary["labels"]?.findIndex((label: any) => label.DDL_ID === labelId);

      if (labelIndex === -1 || !selectedItems.value[labelIndex]) {
        // 标签未被选中 - 无色背景
        return "";
      }

      // 标签被选中，根据数据覆盖情况决定样式
      if (selectedItems.value[labelIndex]) {
        // 检查是否所有选中的数据都拥有此标签
        const selectedRecordIds = dynamicStore.tableSelect.map((item: any) => item.Record_ID);
        const selectedCount = dynamicStore.tableSelect.length;

        if (selectedCount === 0) {
          // 没有选中数据，显示为半色
          return "parent-label-partial-selected";
        }

        // 统计有多少条选中的数据拥有此标签
        const labelRecords = labelStatusData.value.filter(
          (record: any) => record.lable_id === labelId && selectedRecordIds.includes(record.record_id)
        );

        const hasLabelCount = labelRecords.length;

        if (hasLabelCount === 0) {
          // 没有任何数据拥有此标签 - 半色背景（标签被选中但数据没有标签）
          return "parent-label-partial-selected";
        } else if (hasLabelCount === selectedCount) {
          // 所有选中数据都拥有此标签 - 纯色背景
          return "parent-label-full-selected";
        } else {
          // 部分数据拥有此标签 - 半色背景
          return "parent-label-partial-selected";
        }
      }

      return "";
    };
    // 计算子级标签的背景样式类
    const getLabelClass2 = (labelId: string) => {
      // 找到标签在字典中的索引
      const labelIndex = dictionary["labels"]?.findIndex((label: any) => label.DDL_ID === labelId);

      if (labelIndex === -1 || !selectedItems2.value[labelIndex]) {
        // 标签未被选中 - 无色背景
        return "";
      }

      // 标签被选中，根据数据覆盖情况决定样式
      if (selectedItems2.value[labelIndex]) {
        // 检查是否所有选中的数据都拥有此标签
        const selectedRecordIds = dynamicStore.childTableSelect.map((item: any) => item.Record_ID);
        const selectedCount = dynamicStore.childTableSelect.length;

        if (selectedCount === 0) {
          // 没有选中数据，显示为半色
          return "child-label-partial-selected";
        }

        // 统计有多少条选中的数据拥有此标签
        const labelRecords = labelStatusData2.value.filter(
          (record: any) => record.lable_id === labelId && selectedRecordIds.includes(record.record_id)
        );

        const hasLabelCount = labelRecords.length;

        if (hasLabelCount === 0) {
          // 没有任何数据拥有此标签 - 半色背景（标签被选中但数据没有标签）
          return "child-label-partial-selected";
        } else if (hasLabelCount === selectedCount) {
          // 所有选中数据都拥有此标签 - 纯色背景
          return "child-label-full-selected";
        } else {
          // 部分数据拥有此标签 - 半色背景
          return "child-label-partial-selected";
        }
      }

      return "";
    };

    // 表格刷新
    const tableRefresh = () => {
      let catalogId = null;
      let type = 1;
      if (fatherObj) {
        if (dynamicStore.childLeftClick) {
          catalogId = leftTreeObj.value.Catalog_ID;
          type = 1;
        } else {
          if (!dynamicStore.noCatalogStatus) {
            type = 2;
          } else {
            catalogId = null;
            type = 1;
          }
        }
      } else {
        if (!dynamicStore.noCatalogStatus) {
          catalogId = leftTreeObj.value.Catalog_ID;
          type = 1;
        } else {
          catalogId = null;
          type = 1;
        }
      }
      dynamicStore
        .getTableData({
          fmid: routeData.value.fmid,
          fmtid: routeData.value.fmtid,
          catalogid: catalogId,
          status: routeData.value.status,
          searchType: type,
          pageIndex: 1,
          pageSize: dynamicStore.pageSize ? dynamicStore.pageSize : 0,
          parentid: routeData.value.fatherObj
            ? JSON.parse(decodeURIComponent(routeData.value.fatherObj as any)).Record_ID
            : undefined
        })
        .then((res: any) => {
          tableSetting.loading = false;
          dynamicStore.setTableData(res.List);
          dynamicStore.setSourthTableData(res.List);
          if (tableSetting.selectData.length > 0) {
            tableSetting.selectData.forEach(element => {
              if (dynamicStore.tableData.filter(s => s.Record_ID === element.Record_ID).length > 0) {
                dynamicStore.tableData.filter(s => s.Record_ID === element.Record_ID)[0].checkbox = true;
              }
            });
          }
        })
        .catch(() => {
          tableSetting.loading = false;
        });
    };
    // 切换单个标签的选中状态
    const toggleSelection = (index: number) => {
      if (dictionary["labels"] && dictionary["labels"][index]) {
        const labelId = dictionary["labels"][index].DDL_ID;

        // 检查标签当前是否被选中
        const isCurrentlySelected = selectedItems.value[index];

        if (!isCurrentlySelected) {
          // 标签当前未被选中，点击后直接变为全色（为所有数据添加标签）
          selectedItems.value[index] = true;
          if (!selectedLabelIds.value.includes(labelId)) {
            selectedLabelIds.value.push(labelId);
          }

          // 为所有选中的数据添加这个标签，使其变为全色
          const selectedRecordIds = dynamicStore.tableSelect.map((item: any) => item.Record_ID);
          selectedRecordIds.forEach(recordId => {
            // 检查这条数据是否已经有这个标签
            const existingRecord = labelStatusData.value.find(
              (record: any) => record.record_id === recordId && record.lable_id === labelId
            );

            if (!existingRecord) {
              // 如果数据没有这个标签，则添加
              labelStatusData.value.push({
                record_id: recordId,
                lable_id: labelId,
                fmt_id: routeData.value.fmtid,
                lable_Create_Time: new Date().toISOString()
              });
            }
          });
        } else {
          // 标签当前已被选中，检查数据覆盖情况
          const selectedRecordIds = dynamicStore.tableSelect.map((item: any) => item.Record_ID);
          const selectedCount = dynamicStore.tableSelect.length;

          // 统计有多少条选中的数据拥有这个标签
          const labelRecords = labelStatusData.value.filter(
            (record: any) => record.lable_id === labelId && selectedRecordIds.includes(record.record_id)
          );
          const hasLabelCount = labelRecords.length;

          if (hasLabelCount === selectedCount && selectedCount > 0) {
            // 当前是全色状态，点击后变为无色（取消选中）
            selectedItems.value[index] = false;
            const labelIndex = selectedLabelIds.value.indexOf(labelId);
            if (labelIndex > -1) {
              selectedLabelIds.value.splice(labelIndex, 1);
            }
          } else {
            // 当前是半色状态，点击后变为全色（全部选中）
            // 为所有选中的数据添加这个标签，使其变为全色
            selectedItems.value[index] = true;
            if (!selectedLabelIds.value.includes(labelId)) {
              selectedLabelIds.value.push(labelId);
            }

            // 为所有选中的数据添加这个标签
            const selectedRecordIds = dynamicStore.tableSelect.map((item: any) => item.Record_ID);
            selectedRecordIds.forEach(recordId => {
              // 检查这条数据是否已经有这个标签
              const existingRecord = labelStatusData.value.find(
                (record: any) => record.record_id === recordId && record.lable_id === labelId
              );

              if (!existingRecord) {
                // 如果数据没有这个标签，则添加
                labelStatusData.value.push({
                  record_id: recordId,
                  lable_id: labelId,
                  fmt_id: routeData.value.fmtid,
                  lable_Create_Time: new Date().toISOString()
                });
              }
            });
          }
        }

        console.log("当前选中的标签IDs:", selectedLabelIds.value);
        console.log(
          "标签名称:",
          selectedLabelIds.value.map(id => {
            const label = dictionary["labels"].find((item: any) => item.DDL_ID === id);
            return label ? label.DDL_Name : id;
          })
        );

        // 根据选中的标签获取数据
        if (LabelSearchSetting.visible) {
          if (selectedLabelIds.value.length > 0) {
            proxy.$vueAxios
              .post("Dynamic/GetDataByLabelIds", {
                labelIds: selectedLabelIds.value.join(","),
                fmtId: routeData.value.fmtid
              })
              .then((res: any) => {
                if (res.Mark) {
                  console.log(
                    "record_id数据:",
                    res.List.map((item: any) => item.record_id)
                  );
                  // 将筛选后的数据重新赋值给tableData
                  dynamicStore.setTableData(res.List);
                } else {
                  console.log("接口请求失败，清空表格");
                  dynamicStore.setTableData([]);
                }
              });
          } else {
            // 所有标签都未选中时，恢复原始数据
            console.log("所有标签都未选中，恢复原始数据");
            dynamicStore.setTableData(dynamicStore.sourthTableData);
          }
        }
      }
    };
    // 切换单个标签的选中状态
    const toggleSelection2 = (index: number) => {
      if (dictionary["labels"] && dictionary["labels"][index]) {
        const labelId = dictionary["labels"][index].DDL_ID;

        // 检查标签当前是否被选中
        const isCurrentlySelected = selectedItems2.value[index];

        if (!isCurrentlySelected) {
          // 标签当前未被选中，点击后直接变为全色（为所有数据添加标签）
          selectedItems2.value[index] = true;
          if (!selectedLabelIds2.value.includes(labelId)) {
            selectedLabelIds2.value.push(labelId);
          }

          // 为所有选中的数据添加这个标签，使其变为全色
          const selectedRecordIds = dynamicStore.childTableSelect.map((item: any) => item.Record_ID);
          selectedRecordIds.forEach(recordId => {
            // 检查这条数据是否已经有这个标签
            const existingRecord = labelStatusData2.value.find(
              (record: any) => record.record_id === recordId && record.lable_id === labelId
            );

            if (!existingRecord) {
              // 如果数据没有这个标签，则添加
              labelStatusData2.value.push({
                record_id: recordId,
                lable_id: labelId,
                fmt_id: routeData.value.fmtid,
                lable_Create_Time: new Date().toISOString()
              });
            }
          });
        } else {
          // 标签当前已被选中，检查数据覆盖情况
          const selectedRecordIds = dynamicStore.childTableSelect.map((item: any) => item.Record_ID);
          const selectedCount = dynamicStore.childTableSelect.length;

          // 统计有多少条选中的数据拥有这个标签
          const labelRecords = labelStatusData2.value.filter(
            (record: any) => record.lable_id === labelId && selectedRecordIds.includes(record.record_id)
          );
          const hasLabelCount = labelRecords.length;

          if (hasLabelCount === selectedCount && selectedCount > 0) {
            // 当前是全色状态，点击后变为无色（取消选中）
            selectedItems2.value[index] = false;
            const labelIndex = selectedLabelIds2.value.indexOf(labelId);
            if (labelIndex > -1) {
              selectedLabelIds2.value.splice(labelIndex, 1);
            }
          } else {
            // 当前是半色状态，点击后变为全色（全部选中）
            // 为所有选中的数据添加这个标签，使其变为全色
            selectedItems2.value[index] = true;
            if (!selectedLabelIds2.value.includes(labelId)) {
              selectedLabelIds2.value.push(labelId);
            }

            // 为所有选中的数据添加这个标签
            const selectedRecordIds = dynamicStore.childTableSelect.map((item: any) => item.Record_ID);
            selectedRecordIds.forEach(recordId => {
              // 检查这条数据是否已经有这个标签
              const existingRecord = labelStatusData2.value.find(
                (record: any) => record.record_id === recordId && record.lable_id === labelId
              );

              if (!existingRecord) {
                // 如果数据没有这个标签，则添加
                labelStatusData2.value.push({
                  record_id: recordId,
                  lable_id: labelId,
                  fmt_id: routeData.value.fmtid,
                  lable_Create_Time: new Date().toISOString()
                });
              }
            });
          }
        }

        console.log("当前选中的标签IDs:", selectedLabelIds2.value);
        console.log(
          "标签名称:",
          selectedLabelIds2.value.map(id => {
            const label = dictionary["labels"].find((item: any) => item.DDL_ID === id);
            return label ? label.DDL_Name : id;
          })
        );

        // 根据选中的标签获取数据
        if (LabelSearchSetting2.visible) {
          if (selectedLabelIds2.value.length > 0) {
            proxy.$vueAxios
              .post("Dynamic/GetDataByLabelIds", {
                labelIds: selectedLabelIds2.value.join(","),
                fmtId: childData.value[activeName.value]?.FMT_ID
              })
              .then((res: any) => {
                if (res.Mark) {
                  console.log(
                    "record_id数据:",
                    res.List.map((item: any) => item.record_id)
                  );
                  // 将筛选后的数据重新赋值给tableData
                  dynamicStore.setChildTableData(res.List);
                } else {
                  console.log("接口请求失败，清空表格");
                  dynamicStore.setChildTableData([]);
                }
              });
          } else {
            // 所有标签都未选中时，恢复原始数据
            console.log("所有标签都未选中，恢复原始数据");
            dynamicStore.setChildTableData(dynamicStore.childSourthTableData);
          }
        }
      }
    };
    const activeNames = ref([]);
    const handleChange = (val: string[]) => {
      console.log(val);
    };

    // 滚动到指定的选中行
    const scrollToSelectedRow = (recordId: string) => {
      nextTick(() => {
        if (tabbarRef.value && tabbarRef.value.scrollToRowByRecordId) {
          tabbarRef.value.scrollToRowByRecordId(recordId);
        }
      });
    };

    // 检测主表格数据变化
    watch(
      () => [...dynamicStore.tableData],
      (newValue, oldValue) => {
        if (tabbarRef.value && tabbarRef.value !== "undefined") {
          tabbarRef.value.reloadData(newValue);
        }
      }
    );
    // 检测子级表格数据变化
    watch(
      () => [...dynamicStore.childTableData],
      (newValue, oldValue) => {
        nextTick(() => {
          if (childTabbarRef.value) {
            childTabbarRef.value[activeName.value].reloadData(newValue);
          }
        });
      }
    );
    // 检测路由变化
    watch(
      () => route.query,
      (newVal, oldVal) => {
        routeData.value = newVal;
      },
      { deep: true }
    );
    // 监听组件尺寸
    watch(
      () => globalStore.assemblySize,
      (newVal, oldVal) => {
        const el = document.querySelectorAll(".vxe-grid--toolbar-wrapper") as any;
        if (globalStore.assemblySize === "default") {
          el[0].style.height = "47px";
          el[Number(activeName.value) + 1].style.height = "47px";
        } else if (globalStore.assemblySize === "large") {
          el[0].style.height = "57px";
          el[Number(activeName.value) + 1].style.height = "57px";
        } else if (globalStore.assemblySize === "small") {
          el[0].style.height = "37px";
          el[Number(activeName.value) + 1].style.height = "37px";
        }
      }
    );
    onMounted(() => {
      signalrEvent();
      init();
    });
    return {
      activatedFlag,
      catalogList,
      topBarShow,
      tableHeight,
      headerHeight,
      sumHeight,
      dynamicStore,
      formModel,
      searchFieldData,
      formRef,
      tableSearch,
      route,
      tabbarRef,
      routeData,
      fatherObj,
      dynamicModal,
      self,
      fulltextRef,
      metaDataRef,
      tableSetting,
      drawerSetting,
      childData,
      leftTreeObj,
      QRCode1,
      QRCode2,
      SortModalRef,
      dictionary,
      handoverSetting,
      HandOverModalRef,
      uploadZip,
      uploadConfig,
      fulltextModal,
      childTableSetting,
      globalStore,
      childTabbarRef,
      activeName,
      leftTree,
      reportData,
      childReportData,
      childReportIdData,
      TrailRef,
      TrailConfig,
      FMTData,
      fourAspectShow,
      isShowFourAspectRecords,
      fourAspectConfigs,
      fourAspectRow,
      fourAspectRecordsClickRow,
      fourAspectRef,
      curFourAspectItem,
      allFinish,
      activeIndex,
      AuthConfig,
      mountSetting,
      formData,
      mountForm,
      mountRule,
      mountConfig,
      pasteSetting,
      pasteFormData,
      childHeight,
      childHeaderHeight,
      childTableHeight,
      singalrModal,
      remarkSetting,
      remarkFormData,
      remarkForm,
      dataCheckSetting,
      dataCheckFormData,
      dataCheckForm,
      dataCheckRule,
      ReplacementConfig,
      LSHMoveSetting,
      LSHMoveFormData,
      replaceModal,
      resetLSH,
      resetLSHFormData,
      LHSRule,
      resetLHSRef,
      metaDataSetting,
      dismantleSetting,
      queryTheVolumeSetting,
      queryTheVolumeSelect,
      queryTheVolumeTableSetting,
      queryTheVolumeInput,
      queryTheVolumeRule,
      tableIndex,
      LSHSetting,
      lshTable,
      childButtonList,
      searchSetting,
      recycleStatus,
      urlModal,
      UrlBorrowRef,
      appStore,
      recycleBtnStatus,
      searchRuleList,
      userList,
      rollUpConfig,
      RollUpForm,
      LabelSetting,
      LabelSearchSetting,
      LabelSetting2,
      LabelSearchSetting2,
      selectedItems,
      groupedLabels,
      labelStatusData,
      selectedLabelIds,
      selectedItems2,
      labelStatusData2,
      selectedLabelIds2,
      leftPaneSize,
      middlePaneSize,
      getLabelStatusData,
      getLabelStatusData2,
      getLabelClass,
      getLabelClass2,
      activeNames,
      //函数
      getPageData,
      search,
      handleResize,
      handleMiddleResize,
      reset,
      getSearchField,
      getSearchFieldType,
      trigger,
      init,
      onTreeClick,
      signalrEvent,
      rowClick,
      rowdblClick,
      getColumns,
      tableSelect,
      toSublevel,
      viewFullText,
      buttonClick,
      getChild,
      pageNext,
      pageAll,
      transTree,
      getChildBtnPermission,
      getCatalog,
      exportExcel,
      uploadZipFile,
      fulltextUploadMany,
      childRowClick,
      childRowdblClick,
      childTableSelect,
      childViewFullText,
      childToSublevel,
      childButtonClick,
      tabChange,
      reportExcel,
      childReportExcel,
      getChildReportData,
      menuClick,
      seletedDataHandle,
      stopCheckHandle,
      mountHandle,
      pasteHandle,
      cease,
      cancel,
      remarkHandle,
      remarkChange,
      dataCheckHandle,
      LSHMoveHandle,
      noClassManage,
      resetLSHHandle,
      showFolderMetaData,
      showFourAspectRecords,
      getChildTableData,
      showFileMetaData,
      dismantleHandle,
      queryTheVolumeHandle,
      onQueryTheVolumeTreeClick,
      queryTheVolumeSelectChange,
      queryTheVolumeTableSelect,
      queryTheVolumeInputChange,
      noQueryTheVolumeTreeClassMana,
      resetLSHEvent,
      sortUpLSH,
      sortDownLSH,
      LSHTo,
      LSHandle,
      LSHRowClick,
      searchHandle,
      recycle,
      restore,
      recycleDel,
      urlBorrow,
      getFullTextData,
      tableRefresh,
      LabelHandle,
      LabelHandle2,
      toggleSelection,
      toggleSelection2,
      handleChange,
      scrollToSelectedRow,
      handleParentFileDrop,
      handleChildFileDrop
    };
  }
});
</script>

<style scoped lang="scss">
.main-box {
  .tree {
    height: 100%;

    // width: 260px;
    padding: 0;

    // margin-right: 10px;
    overflow: auto !important;

    /* stylelint-disable-next-line selector-id-pattern */
    :deep(#treeDemo) {
      display: flex !important;
    }
  }
  .table-box {
    width: 100%;
    .table-search {
      min-height: 110px;
      padding: 5px;
    }
    :deep(.el-tabs__content) {
      height: 100%;
    }
    :deep(.el-tabs__header) {
      margin: 0;
      background: #ffffff;
      .el-tabs__item {
        padding-left: 15px;
      }
    }
    .tableWraper {
      position: relative;
    }
    .showIcon {
      position: absolute;
      top: 52px;
      right: 8px;
      z-index: 1001;
    }
  }
}
.btns {
  display: flex;
  justify-content: flex-end;
  margin-bottom: 10px;
}
.queryTheVolume_dialog {
  .splitpanes__pane {
    height: 100%;
  }
  .left {
    display: flex;
    flex-direction: column;
    .queryTheVolume_content_left {
      height: 100%;
      .leftTree {
        height: 100%;
        padding: 0;
        :deep(.el-button) {
          margin-top: 6px;
        }
        :deep(.z-tree) {
          flex: none;
          height: 425px !important;
          overflow-y: auto;
        }
      }
    }
  }
  :deep(.el-dialog) {
    .el-dialog__body {
      display: flex;
      .el-card {
        height: 100%;
        .el-card__body {
          padding: 5px;
        }
      }
    }
  }
}
.queryTheVolume_content {
  flex: 1;
  height: 500px;
}
.queryTheVolume_content_right {
  height: 500px;
  .table-top {
    display: flex;
    align-items: center;
    justify-content: space-between;
    .el-input {
      width: 84%;
    }
  }
  .vxe-grid {
    height: calc(100% - 38px);
    margin-top: 5px;
  }
  :deep(.vxe-grid--table-container) {
    height: 100%;
    .vxe-table {
      height: 100%;
      .vxe-table--body-wrapper {
        height: 420px !important;
      }
    }
  }
}
:deep(.vxe-grid--toolbar-wrapper) {
  height: 0;
}
:deep(.header-button-lf) {
  display: flex;
}
.pasteModal {
  :deep(.el-dialog__body) {
    height: 80px;
  }
}
.pause-status-indicator {
  margin-bottom: 10px;
  text-align: center;
  .el-tag {
    font-size: 12px;
    .el-icon {
      margin-right: 4px;
    }
  }
}
.progress-text {
  margin-top: 10px;
  font-size: 14px;
  color: #606266;
  text-align: center;
}
.search-wrap {
  :deep(.el-date-editor) {
    .el-input__wrapper {
      width: -webkit-fill-available;
    }
  }
}
.label_box {
  // padding: 16px;
  border-radius: 9px;
}
.label_group {
  margin-bottom: 20px;
  &:last-child {
    margin-bottom: 0;
  }
}
.label_group_title {
  padding: 8px 16px;
  margin-bottom: 12px;
  font-size: 16px;
  font-weight: 600;
  color: var(--el-text-color-primary);
  background: #ffffff;
  border-radius: 6px;
}
.label_group_items {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 10px;
}
.label_box_item {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 24px;
  color: var(--el-text-color-primary);
  cursor: pointer;
  background: #ffffff;
  border: 1px solid #e5e5e5;
  border-radius: 6px;
  box-shadow: 0 2px 4px rgb(0 0 0 / 10%);
  transition: all 0.3s ease;
  span {
    width: 60px;
    overflow: hidden;
    text-align: center;
    text-overflow: ellipsis;
    white-space: nowrap;
  }
  &:hover {
    border-color: var(--el-color-primary);
    box-shadow: 0 4px 8px rgb(0 0 0 / 15%);
    transform: translateY(-2px);
  }
  &.selected {
    color: #ffffff;
    background-color: var(--el-color-primary);
    border-color: var(--el-color-primary);
    box-shadow: 0 6px 12px rgb(0 0 0 / 20%);
    transform: translateY(-3px);
  }

  //   // 父级标签样式
  // 全部数据都拥有此标签
  &.parent-label-full-selected {
    color: #ffffff;
    background-color: var(--el-color-primary);
    border-color: var(--el-color-primary);
  }

  // 部分数据拥有此标签 - 从左到右的一半颜色
  &.parent-label-partial-selected {
    color: #333333;
    background: linear-gradient(to right, var(--el-color-primary) 50%, #ffffff 50%);
    border-color: var(--el-color-primary);
  }

  // 子级标签样式
  // 全部数据都拥有此标签
  &.child-label-full-selected {
    color: #ffffff;
    background-color: var(--el-color-primary);
    border-color: var(--el-color-primary);
  }

  // 部分数据拥有此标签 - 从左到右的一半颜色
  &.child-label-partial-selected {
    color: #333333;
    background: linear-gradient(to right, var(--el-color-primary) 50%, #ffffff 50%);
    border-color: var(--el-color-primary);
  }
}
</style>
